Merge branch 'docfix/mix_task_options' into 'develop'
[akkoma] / lib / mix / tasks / pleroma / user.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Mix.Tasks.Pleroma.User do
6 use Mix.Task
7 import Ecto.Changeset
8 import Mix.Pleroma
9 alias Pleroma.User
10 alias Pleroma.UserInviteToken
11 alias Pleroma.Web.OAuth
12
13 @shortdoc "Manages Pleroma users"
14 @moduledoc """
15 Manages Pleroma users.
16
17 ## Create a new user.
18
19 mix pleroma.user new NICKNAME EMAIL [OPTION...]
20
21 Options:
22 - `--name NAME` - the user's name (i.e., "Lain Iwakura")
23 - `--bio BIO` - the user's bio
24 - `--password PASSWORD` - the user's password
25 - `--moderator`/`--no-moderator` - whether the user is a moderator
26 - `--admin`/`--no-admin` - whether the user is an admin
27 - `-y`, `--assume-yes`/`--no-assume-yes` - whether to assume yes to all questions
28
29 ## Generate an invite link.
30
31 mix pleroma.user invite [OPTION...]
32
33 Options:
34 - `--expires-at DATE` - last day on which token is active (e.g. "2019-04-05")
35 - `--max-use NUMBER` - maximum numbers of token uses
36
37 ## List generated invites
38
39 mix pleroma.user invites
40
41 ## Revoke invite
42
43 mix pleroma.user revoke_invite TOKEN OR TOKEN_ID
44
45 ## Delete the user's account.
46
47 mix pleroma.user rm NICKNAME
48
49 ## Delete the user's activities.
50
51 mix pleroma.user delete_activities NICKNAME
52
53 ## Sign user out from all applications (delete user's OAuth tokens and authorizations).
54
55 mix pleroma.user sign_out NICKNAME
56
57 ## Deactivate or activate the user's account.
58
59 mix pleroma.user toggle_activated NICKNAME
60
61 ## Unsubscribe local users from user's account and deactivate it
62
63 mix pleroma.user unsubscribe NICKNAME
64
65 ## Unsubscribe local users from an entire instance and deactivate all accounts
66
67 mix pleroma.user unsubscribe_all_from_instance INSTANCE
68
69 ## Create a password reset link.
70
71 mix pleroma.user reset_password NICKNAME
72
73 ## Set the value of the given user's settings.
74
75 mix pleroma.user set NICKNAME [OPTION...]
76
77 Options:
78 - `--locked`/`--no-locked` - whether the user's account is locked
79 - `--moderator`/`--no-moderator` - whether the user is a moderator
80 - `--admin`/`--no-admin` - whether the user is an admin
81
82 ## Add tags to a user.
83
84 mix pleroma.user tag NICKNAME TAGS
85
86 ## Delete tags from a user.
87
88 mix pleroma.user untag NICKNAME TAGS
89
90 ## Toggle confirmation of the user's account.
91
92 mix pleroma.user toggle_confirmed NICKNAME
93 """
94 def run(["new", nickname, email | rest]) do
95 {options, [], []} =
96 OptionParser.parse(
97 rest,
98 strict: [
99 name: :string,
100 bio: :string,
101 password: :string,
102 moderator: :boolean,
103 admin: :boolean,
104 assume_yes: :boolean
105 ],
106 aliases: [
107 y: :assume_yes
108 ]
109 )
110
111 name = Keyword.get(options, :name, nickname)
112 bio = Keyword.get(options, :bio, "")
113
114 {password, generated_password?} =
115 case Keyword.get(options, :password) do
116 nil ->
117 {:crypto.strong_rand_bytes(16) |> Base.encode64(), true}
118
119 password ->
120 {password, false}
121 end
122
123 moderator? = Keyword.get(options, :moderator, false)
124 admin? = Keyword.get(options, :admin, false)
125 assume_yes? = Keyword.get(options, :assume_yes, false)
126
127 shell_info("""
128 A user will be created with the following information:
129 - nickname: #{nickname}
130 - email: #{email}
131 - password: #{
132 if(generated_password?, do: "[generated; a reset link will be created]", else: password)
133 }
134 - name: #{name}
135 - bio: #{bio}
136 - moderator: #{if(moderator?, do: "true", else: "false")}
137 - admin: #{if(admin?, do: "true", else: "false")}
138 """)
139
140 proceed? = assume_yes? or shell_yes?("Continue?")
141
142 if proceed? do
143 start_pleroma()
144
145 params = %{
146 nickname: nickname,
147 email: email,
148 password: password,
149 password_confirmation: password,
150 name: name,
151 bio: bio
152 }
153
154 changeset = User.register_changeset(%User{}, params, need_confirmation: false)
155 {:ok, _user} = User.register(changeset)
156
157 shell_info("User #{nickname} created")
158
159 if moderator? do
160 run(["set", nickname, "--moderator"])
161 end
162
163 if admin? do
164 run(["set", nickname, "--admin"])
165 end
166
167 if generated_password? do
168 run(["reset_password", nickname])
169 end
170 else
171 shell_info("User will not be created.")
172 end
173 end
174
175 def run(["rm", nickname]) do
176 start_pleroma()
177
178 with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
179 User.perform(:delete, user)
180 shell_info("User #{nickname} deleted.")
181 else
182 _ ->
183 shell_error("No local user #{nickname}")
184 end
185 end
186
187 def run(["toggle_activated", nickname]) do
188 start_pleroma()
189
190 with %User{} = user <- User.get_cached_by_nickname(nickname) do
191 {:ok, user} = User.deactivate(user, !user.info.deactivated)
192
193 shell_info(
194 "Activation status of #{nickname}: #{if(user.info.deactivated, do: "de", else: "")}activated"
195 )
196 else
197 _ ->
198 shell_error("No user #{nickname}")
199 end
200 end
201
202 def run(["reset_password", nickname]) do
203 start_pleroma()
204
205 with %User{local: true} = user <- User.get_cached_by_nickname(nickname),
206 {:ok, token} <- Pleroma.PasswordResetToken.create_token(user) do
207 shell_info("Generated password reset token for #{user.nickname}")
208
209 IO.puts(
210 "URL: #{
211 Pleroma.Web.Router.Helpers.reset_password_url(
212 Pleroma.Web.Endpoint,
213 :reset,
214 token.token
215 )
216 }"
217 )
218 else
219 _ ->
220 shell_error("No local user #{nickname}")
221 end
222 end
223
224 def run(["unsubscribe", nickname]) do
225 start_pleroma()
226
227 with %User{} = user <- User.get_cached_by_nickname(nickname) do
228 shell_info("Deactivating #{user.nickname}")
229 User.deactivate(user)
230
231 {:ok, friends} = User.get_friends(user)
232
233 Enum.each(friends, fn friend ->
234 user = User.get_cached_by_id(user.id)
235
236 shell_info("Unsubscribing #{friend.nickname} from #{user.nickname}")
237 User.unfollow(user, friend)
238 end)
239
240 :timer.sleep(500)
241
242 user = User.get_cached_by_id(user.id)
243
244 if Enum.empty?(user.following) do
245 shell_info("Successfully unsubscribed all followers from #{user.nickname}")
246 end
247 else
248 _ ->
249 shell_error("No user #{nickname}")
250 end
251 end
252
253 def run(["unsubscribe_all_from_instance", instance]) do
254 start_pleroma()
255
256 Pleroma.User.Query.build(%{nickname: "@#{instance}"})
257 |> Pleroma.RepoStreamer.chunk_stream(500)
258 |> Stream.each(fn users ->
259 users
260 |> Enum.each(fn user ->
261 run(["unsubscribe", user.nickname])
262 end)
263 end)
264 |> Stream.run()
265 end
266
267 def run(["set", nickname | rest]) do
268 start_pleroma()
269
270 {options, [], []} =
271 OptionParser.parse(
272 rest,
273 strict: [
274 moderator: :boolean,
275 admin: :boolean,
276 locked: :boolean
277 ]
278 )
279
280 with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
281 user =
282 case Keyword.get(options, :moderator) do
283 nil -> user
284 value -> set_moderator(user, value)
285 end
286
287 user =
288 case Keyword.get(options, :locked) do
289 nil -> user
290 value -> set_locked(user, value)
291 end
292
293 _user =
294 case Keyword.get(options, :admin) do
295 nil -> user
296 value -> set_admin(user, value)
297 end
298 else
299 _ ->
300 shell_error("No local user #{nickname}")
301 end
302 end
303
304 def run(["tag", nickname | tags]) do
305 start_pleroma()
306
307 with %User{} = user <- User.get_cached_by_nickname(nickname) do
308 user = user |> User.tag(tags)
309
310 shell_info("Tags of #{user.nickname}: #{inspect(tags)}")
311 else
312 _ ->
313 shell_error("Could not change user tags for #{nickname}")
314 end
315 end
316
317 def run(["untag", nickname | tags]) do
318 start_pleroma()
319
320 with %User{} = user <- User.get_cached_by_nickname(nickname) do
321 user = user |> User.untag(tags)
322
323 shell_info("Tags of #{user.nickname}: #{inspect(tags)}")
324 else
325 _ ->
326 shell_error("Could not change user tags for #{nickname}")
327 end
328 end
329
330 def run(["invite" | rest]) do
331 {options, [], []} =
332 OptionParser.parse(rest,
333 strict: [
334 expires_at: :string,
335 max_use: :integer
336 ]
337 )
338
339 options =
340 options
341 |> Keyword.update(:expires_at, {:ok, nil}, fn
342 nil -> {:ok, nil}
343 val -> Date.from_iso8601(val)
344 end)
345 |> Enum.into(%{})
346
347 start_pleroma()
348
349 with {:ok, val} <- options[:expires_at],
350 options = Map.put(options, :expires_at, val),
351 {:ok, invite} <- UserInviteToken.create_invite(options) do
352 shell_info("Generated user invite token " <> String.replace(invite.invite_type, "_", " "))
353
354 url =
355 Pleroma.Web.Router.Helpers.redirect_url(
356 Pleroma.Web.Endpoint,
357 :registration_page,
358 invite.token
359 )
360
361 IO.puts(url)
362 else
363 error ->
364 shell_error("Could not create invite token: #{inspect(error)}")
365 end
366 end
367
368 def run(["invites"]) do
369 start_pleroma()
370
371 shell_info("Invites list:")
372
373 UserInviteToken.list_invites()
374 |> Enum.each(fn invite ->
375 expire_info =
376 with expires_at when not is_nil(expires_at) <- invite.expires_at do
377 " | Expires at: #{Date.to_string(expires_at)}"
378 end
379
380 using_info =
381 with max_use when not is_nil(max_use) <- invite.max_use do
382 " | Max use: #{max_use} Left use: #{max_use - invite.uses}"
383 end
384
385 shell_info(
386 "ID: #{invite.id} | Token: #{invite.token} | Token type: #{invite.invite_type} | Used: #{
387 invite.used
388 }#{expire_info}#{using_info}"
389 )
390 end)
391 end
392
393 def run(["revoke_invite", token]) do
394 start_pleroma()
395
396 with {:ok, invite} <- UserInviteToken.find_by_token(token),
397 {:ok, _} <- UserInviteToken.update_invite(invite, %{used: true}) do
398 shell_info("Invite for token #{token} was revoked.")
399 else
400 _ -> shell_error("No invite found with token #{token}")
401 end
402 end
403
404 def run(["delete_activities", nickname]) do
405 start_pleroma()
406
407 with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
408 {:ok, _} = User.delete_user_activities(user)
409 shell_info("User #{nickname} statuses deleted.")
410 else
411 _ ->
412 shell_error("No local user #{nickname}")
413 end
414 end
415
416 def run(["toggle_confirmed", nickname]) do
417 start_pleroma()
418
419 with %User{} = user <- User.get_cached_by_nickname(nickname) do
420 {:ok, user} = User.toggle_confirmation(user)
421
422 message = if user.info.confirmation_pending, do: "needs", else: "doesn't need"
423
424 shell_info("#{nickname} #{message} confirmation.")
425 else
426 _ ->
427 shell_error("No local user #{nickname}")
428 end
429 end
430
431 def run(["sign_out", nickname]) do
432 start_pleroma()
433
434 with %User{local: true} = user <- User.get_cached_by_nickname(nickname) do
435 OAuth.Token.delete_user_tokens(user)
436 OAuth.Authorization.delete_user_authorizations(user)
437
438 shell_info("#{nickname} signed out from all apps.")
439 else
440 _ ->
441 shell_error("No local user #{nickname}")
442 end
443 end
444
445 defp set_moderator(user, value) do
446 info_cng = User.Info.admin_api_update(user.info, %{is_moderator: value})
447
448 user_cng =
449 Ecto.Changeset.change(user)
450 |> put_embed(:info, info_cng)
451
452 {:ok, user} = User.update_and_set_cache(user_cng)
453
454 shell_info("Moderator status of #{user.nickname}: #{user.info.is_moderator}")
455 user
456 end
457
458 defp set_admin(user, value) do
459 info_cng = User.Info.admin_api_update(user.info, %{is_admin: value})
460
461 user_cng =
462 Ecto.Changeset.change(user)
463 |> put_embed(:info, info_cng)
464
465 {:ok, user} = User.update_and_set_cache(user_cng)
466
467 shell_info("Admin status of #{user.nickname}: #{user.info.is_admin}")
468 user
469 end
470
471 defp set_locked(user, value) do
472 info_cng = User.Info.user_upgrade(user.info, %{locked: value})
473
474 user_cng =
475 Ecto.Changeset.change(user)
476 |> put_embed(:info, info_cng)
477
478 {:ok, user} = User.update_and_set_cache(user_cng)
479
480 shell_info("Locked status of #{user.nickname}: #{user.info.locked}")
481 user
482 end
483 end