users_controller.rb 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class UsersController < ApplicationController
  3. include ChecksUserAttributesByCurrentUserPermission
  4. include CanPaginate
  5. prepend_before_action -> { authorize! }, only: %i[import_example import_start search history unlock]
  6. prepend_before_action :authentication_check, except: %i[create password_reset_send password_reset_verify image email_verify email_verify_send admin_password_auth_send admin_password_auth_verify]
  7. prepend_before_action :authentication_check_only, only: %i[create]
  8. # @path [GET] /users
  9. #
  10. # @summary Returns a list of User records.
  11. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  12. # get a list of all Users. If the requester is in the
  13. # role 'Customer' only just the own User record will be returned.
  14. #
  15. # @response_message 200 [Array<User>] List of matching User records.
  16. # @response_message 403 Forbidden / Invalid session.
  17. def index
  18. users = policy_scope(User).reorder(id: :asc).offset(pagination.offset).limit(pagination.limit)
  19. if response_expand?
  20. list = users.map(&:attributes_with_association_names)
  21. render json: list, status: :ok
  22. return
  23. end
  24. if response_full?
  25. assets = {}
  26. item_ids = []
  27. users.each do |item|
  28. item_ids.push item.id
  29. assets = item.assets(assets)
  30. end
  31. render json: {
  32. record_ids: item_ids,
  33. assets: assets,
  34. }, status: :ok
  35. return
  36. end
  37. users_all = users.map do |user|
  38. User.lookup(id: user.id).attributes_with_association_ids
  39. end
  40. render json: users_all, status: :ok
  41. end
  42. # @path [GET] /users/{id}
  43. #
  44. # @summary Returns the User record with the requested identifier.
  45. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  46. # access all User records. If the requester is in the
  47. # role 'Customer' just the own User record is accessable.
  48. #
  49. # @parameter id(required) [Integer] The identifier matching the requested User.
  50. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  51. #
  52. # @response_message 200 [User] User record matching the requested identifier.
  53. # @response_message 403 Forbidden / Invalid session.
  54. def show
  55. user = User.find(params[:id])
  56. authorize!(user)
  57. if response_expand?
  58. result = user.attributes_with_association_names
  59. result.delete('password')
  60. render json: result
  61. return
  62. end
  63. if response_full?
  64. result = {
  65. id: user.id,
  66. assets: user.assets({}),
  67. }
  68. render json: result
  69. return
  70. end
  71. result = user.attributes_with_association_ids
  72. result.delete('password')
  73. render json: result
  74. end
  75. # @path [POST] /users
  76. #
  77. # @summary processes requests as CRUD-like record creation, admin creation or user signup depending on circumstances
  78. # @see #create_internal #create_admin #create_signup
  79. def create
  80. if current_user
  81. create_internal
  82. elsif params[:signup]
  83. create_signup
  84. else
  85. create_admin
  86. end
  87. end
  88. # @path [PUT] /users/{id}
  89. #
  90. # @summary Updates the User record matching the identifier with the provided attribute values.
  91. # @notes TODO.
  92. #
  93. # @parameter id(required) [Integer] The identifier matching the requested User record.
  94. # @parameter User(required,body) [User] The attribute value structure needed to update a User record.
  95. #
  96. # @response_message 200 [User] Updated User record.
  97. # @response_message 403 Forbidden / Invalid session.
  98. def update
  99. user = User.find(params[:id])
  100. authorize!(user)
  101. # permission check
  102. check_attributes_by_current_user_permission(params)
  103. user.with_lock do
  104. clean_params = User.association_name_to_id_convert(params)
  105. clean_params = User.param_cleanup(clean_params, true)
  106. clean_params[:screen] = 'edit'
  107. # presence and permissions were checked via `check_attributes_by_current_user_permission`
  108. privileged_attributes = params.slice(:role_ids, :roles, :group_ids, :groups, :organization_ids, :organizations)
  109. if privileged_attributes.present?
  110. user.associations_from_param(privileged_attributes)
  111. end
  112. user.update!(clean_params)
  113. end
  114. if response_expand?
  115. user = user.reload.attributes_with_association_names
  116. user.delete('password')
  117. render json: user, status: :ok
  118. return
  119. end
  120. if response_full?
  121. result = {
  122. id: user.id,
  123. assets: user.assets({}),
  124. }
  125. render json: result, status: :ok
  126. return
  127. end
  128. user = user.reload.attributes_with_association_ids
  129. user.delete('password')
  130. render json: user, status: :ok
  131. end
  132. # @path [DELETE] /users/{id}
  133. #
  134. # @summary Deletes the User record matching the given identifier.
  135. # @notes The requester has to be in the role 'Admin' to be able to delete a User record.
  136. #
  137. # @parameter id(required) [User] The identifier matching the requested User record.
  138. #
  139. # @response_message 200 User successfully deleted.
  140. # @response_message 403 Forbidden / Invalid session.
  141. def destroy
  142. user = User.find(params[:id])
  143. authorize!(user)
  144. model_references_check(User, params)
  145. model_destroy_render(User, params)
  146. end
  147. # @path [GET] /users/me
  148. #
  149. # @summary Returns the User record of current user.
  150. # @notes The requester needs to have a valid authentication.
  151. #
  152. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  153. #
  154. # @response_message 200 [User] User record matching the requested identifier.
  155. # @response_message 403 Forbidden / Invalid session.
  156. def me
  157. if response_expand?
  158. user = current_user.attributes_with_association_names
  159. user.delete('password')
  160. render json: user, status: :ok
  161. return
  162. end
  163. if response_full?
  164. full = User.full(current_user.id)
  165. render json: full
  166. return
  167. end
  168. user = current_user.attributes_with_association_ids
  169. user.delete('password')
  170. render json: user
  171. end
  172. # @path [GET] /users/search
  173. #
  174. # @tag Search
  175. # @tag User
  176. #
  177. # @summary Searches the User matching the given expression(s).
  178. # @notes TODO: It's possible to use the SOLR search syntax.
  179. # The requester has to be in the role 'Admin' or 'Agent' to
  180. # be able to search for User records.
  181. #
  182. # @parameter query [String] The search query.
  183. # @parameter limit [Integer] The limit of search results.
  184. # @parameter ids(multi) [Array<Integer>] A list of User IDs which should be returned
  185. # @parameter role_ids(multi) [Array<Integer>] A list of Role identifiers to which the Users have to be allocated to.
  186. # @parameter group_ids(multi) [Hash<String=>Integer,Array<Integer>>] A list of Group identifiers to which the Users have to be allocated to.
  187. # @parameter permissions(multi) [Array<String>] A list of Permission identifiers to which the Users have to be allocated to.
  188. # @parameter full [Boolean] Defines if the result should be
  189. # true: { user_ids => [1,2,...], assets => {...} }
  190. # or false: [{:id => user.id, :label => "firstname lastname <email>", :value => "firstname lastname <email>"},...].
  191. #
  192. # @response_message 200 [Array<User>] A list of User records matching the search term.
  193. # @response_message 403 Forbidden / Invalid session.
  194. def search
  195. model_search_render(User, params)
  196. end
  197. # @path [GET] /users/history/{id}
  198. #
  199. # @tag History
  200. # @tag User
  201. #
  202. # @summary Returns the History records of a User record matching the given identifier.
  203. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  204. # get the History records of a User record.
  205. #
  206. # @parameter id(required) [Integer] The identifier matching the requested User record.
  207. #
  208. # @response_message 200 [History] The History records of the requested User record.
  209. # @response_message 403 Forbidden / Invalid session.
  210. def history
  211. # get user data
  212. user = User.find(params[:id])
  213. # get history of user
  214. render json: user.history_get(true)
  215. end
  216. # @path [PUT] /users/unlock/{id}
  217. #
  218. # @summary Unlocks the User record matching the identifier.
  219. # @notes The requester have 'admin.user' permissions to be able to unlock a user.
  220. #
  221. # @parameter id(required) [Integer] The identifier matching the requested User record.
  222. #
  223. # @response_message 200 Unlocked User record.
  224. # @response_message 403 Forbidden / Invalid session.
  225. def unlock
  226. user = User.find(params[:id])
  227. user.with_lock do
  228. user.update!(login_failed: 0)
  229. end
  230. render json: { message: 'ok' }, status: :ok
  231. end
  232. =begin
  233. Resource:
  234. POST /api/v1/users/email_verify
  235. Payload:
  236. {
  237. "token": "SoMeToKeN",
  238. }
  239. Response:
  240. {
  241. :message => 'ok'
  242. }
  243. Test:
  244. curl http://localhost/api/v1/users/email_verify -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"token": "SoMeToKeN"}'
  245. =end
  246. def email_verify
  247. raise Exceptions::UnprocessableEntity, __('No token!') if !params[:token]
  248. verify = Service::User::SignupVerify.new(token: params[:token], current_user: current_user)
  249. begin
  250. user = verify.execute
  251. rescue Service::CheckFeatureEnabled::FeatureDisabledError, Service::User::SignupVerify::InvalidTokenError => e
  252. raise Exceptions::UnprocessableEntity, e.message
  253. end
  254. current_user_set(user) if user
  255. msg = user ? { message: 'ok', user_email: user.email } : { message: 'failed' }
  256. render json: msg, status: :ok
  257. end
  258. =begin
  259. Resource:
  260. POST /api/v1/users/email_verify_send
  261. Payload:
  262. {
  263. "email": "some_email@example.com"
  264. }
  265. Response:
  266. {
  267. :message => 'ok'
  268. }
  269. Test:
  270. curl http://localhost/api/v1/users/email_verify_send -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"email": "some_email@example.com"}'
  271. =end
  272. def email_verify_send
  273. raise Exceptions::UnprocessableEntity, __('No email!') if !params[:email]
  274. signup = Service::User::Deprecated::Signup.new(user_data: { email: params[:email] }, resend: true)
  275. begin
  276. signup.execute
  277. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  278. raise Exceptions::UnprocessableEntity, e.message
  279. rescue Service::User::Signup::TokenGenerationError
  280. render json: { message: 'failed' }, status: :ok
  281. end
  282. # Result is always positive to avoid leaking of existing user accounts.
  283. render json: { message: 'ok' }, status: :ok
  284. end
  285. =begin
  286. Resource:
  287. POST /api/v1/users/admin_login
  288. Payload:
  289. {
  290. "username": "some user name"
  291. }
  292. Response:
  293. {
  294. :message => 'ok'
  295. }
  296. Test:
  297. curl http://localhost/api/v1/users/admin_login -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  298. =end
  299. def admin_password_auth_send
  300. raise Exceptions::UnprocessableEntity, 'username param needed!' if params[:username].blank?
  301. send = Service::Auth::Deprecated::SendAdminToken.new(login: params[:username])
  302. begin
  303. send.execute
  304. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  305. raise Exceptions::UnprocessableEntity, e.message
  306. rescue Service::Auth::Deprecated::SendAdminToken::TokenError, Service::Auth::Deprecated::SendAdminToken::EmailError
  307. render json: { message: 'failed' }, status: :ok
  308. return
  309. end
  310. render json: { message: 'ok' }, status: :ok
  311. end
  312. def admin_password_auth_verify
  313. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  314. verify = Service::Auth::VerifyAdminToken.new(token: params[:token])
  315. user = begin
  316. verify.execute
  317. rescue => e
  318. raise Exceptions::UnprocessableEntity, e.message
  319. end
  320. msg = user ? { message: 'ok', user_login: user.login } : { message: 'failed' }
  321. render json: msg, status: :ok
  322. end
  323. =begin
  324. Resource:
  325. POST /api/v1/users/password_reset
  326. Payload:
  327. {
  328. "username": "some user name"
  329. }
  330. Response:
  331. {
  332. :message => 'ok'
  333. }
  334. Test:
  335. curl http://localhost/api/v1/users/password_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  336. =end
  337. def password_reset_send
  338. raise Exceptions::UnprocessableEntity, 'username param needed!' if params[:username].blank?
  339. send = Service::User::PasswordReset::Deprecated::Send.new(username: params[:username])
  340. begin
  341. send.execute
  342. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  343. raise Exceptions::UnprocessableEntity, e.message
  344. rescue Service::User::PasswordReset::Send::EmailError
  345. render json: { message: 'failed' }, status: :ok
  346. return
  347. end
  348. # Result is always positive to avoid leaking of existing user accounts.
  349. render json: { message: 'ok' }, status: :ok
  350. end
  351. =begin
  352. Resource:
  353. POST /api/v1/users/password_reset_verify
  354. Payload:
  355. {
  356. "token": "SoMeToKeN",
  357. "password": "new_pw"
  358. }
  359. Response:
  360. {
  361. :message => 'ok'
  362. }
  363. Test:
  364. curl http://localhost/api/v1/users/password_reset_verify -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"token": "SoMeToKeN", "password": "new_pw"}'
  365. =end
  366. def password_reset_verify
  367. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  368. # If no password is given, verify token only.
  369. if params[:password].blank?
  370. verify = Service::User::PasswordReset::Verify.new(token: params[:token])
  371. begin
  372. user = verify.execute
  373. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  374. raise Exceptions::UnprocessableEntity, e.message
  375. rescue Service::User::PasswordReset::Verify::InvalidTokenError
  376. render json: { message: 'failed' }, status: :ok
  377. return
  378. end
  379. render json: { message: 'ok', user_login: user.login }, status: :ok
  380. return
  381. end
  382. update = Service::User::PasswordReset::Update.new(token: params[:token], password: params[:password])
  383. begin
  384. user = update.execute
  385. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  386. raise Exceptions::UnprocessableEntity, e.message
  387. rescue Service::User::PasswordReset::Update::InvalidTokenError, Service::User::PasswordReset::Update::EmailError
  388. render json: { message: 'failed' }, status: :ok
  389. return
  390. rescue PasswordPolicy::Error => e
  391. render json: { message: 'failed', notice: e.metadata }, status: :ok
  392. return
  393. end
  394. render json: { message: 'ok', user_login: user.login }, status: :ok
  395. end
  396. =begin
  397. Resource:
  398. POST /api/v1/users/password_change
  399. Payload:
  400. {
  401. "password_old": "old_pw",
  402. "password_new": "new_pw"
  403. }
  404. Response:
  405. {
  406. :message => 'ok'
  407. }
  408. Test:
  409. curl http://localhost/api/v1/users/password_change -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"password_old": "old_pw", "password_new": "new_pw"}'
  410. =end
  411. def password_change
  412. # check old password
  413. if !params[:password_old] || !PasswordPolicy::MaxLength.valid?(params[:password_old])
  414. render json: { message: 'failed', notice: [__('Please provide your current password.')] }, status: :unprocessable_entity
  415. return
  416. end
  417. # set new password
  418. if !params[:password_new]
  419. render json: { message: 'failed', notice: [__('Please provide your new password.')] }, status: :unprocessable_entity
  420. return
  421. end
  422. begin
  423. Service::User::ChangePassword.new(
  424. user: current_user,
  425. current_password: params[:password_old],
  426. new_password: params[:password_new]
  427. ).execute
  428. rescue PasswordPolicy::Error => e
  429. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  430. return
  431. rescue PasswordHash::Error
  432. render json: { message: 'failed', notice: [__('The current password you provided is incorrect.')] }, status: :unprocessable_entity
  433. return
  434. end
  435. render json: { message: 'ok', user_login: current_user.login }, status: :ok
  436. end
  437. def password_check
  438. raise Exceptions::UnprocessableEntity, __("The required parameter 'password' is missing.") if params[:password].blank?
  439. password_check = Service::User::PasswordCheck.new(user: current_user, password: params[:password])
  440. render json: { success: password_check.execute }, status: :ok
  441. end
  442. =begin
  443. Resource:
  444. PUT /api/v1/users/preferences
  445. Payload:
  446. {
  447. "language": "de",
  448. "notification": true
  449. }
  450. Response:
  451. {
  452. :message => 'ok'
  453. }
  454. Test:
  455. curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  456. =end
  457. def preferences
  458. preferences_params = params.except(:controller, :action)
  459. if preferences_params.present?
  460. user = User.find(current_user.id)
  461. user.with_lock do
  462. preferences_params.permit!.to_h.each do |key, value|
  463. user.preferences[key.to_sym] = value
  464. end
  465. user.save!
  466. end
  467. end
  468. render json: { message: 'ok' }, status: :ok
  469. end
  470. =begin
  471. Resource:
  472. POST /api/v1/users/preferences_reset
  473. Response:
  474. {
  475. :message => 'ok'
  476. }
  477. Test:
  478. curl http://localhost/api/v1/users/preferences_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST'
  479. =end
  480. def preferences_notifications_reset
  481. User.reset_notifications_preferences!(current_user)
  482. render json: { message: 'ok' }, status: :ok
  483. end
  484. =begin
  485. Resource:
  486. PUT /api/v1/users/out_of_office
  487. Payload:
  488. {
  489. "out_of_office": true,
  490. "out_of_office_start_at": true,
  491. "out_of_office_end_at": true,
  492. "out_of_office_replacement_id": 123,
  493. "out_of_office_text": 'honeymoon'
  494. }
  495. Response:
  496. {
  497. :message => 'ok'
  498. }
  499. Test:
  500. curl http://localhost/api/v1/users/out_of_office -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"out_of_office": true, "out_of_office_replacement_id": 123}'
  501. =end
  502. def out_of_office
  503. user = User.find(current_user.id)
  504. Service::User::OutOfOffice
  505. .new(user,
  506. enabled: params[:out_of_office],
  507. start_at: params[:out_of_office_start_at],
  508. end_at: params[:out_of_office_end_at],
  509. replacement: User.find_by(id: params[:out_of_office_replacement_id]),
  510. text: params[:out_of_office_text])
  511. .execute
  512. render json: { message: 'ok' }, status: :ok
  513. end
  514. =begin
  515. Resource:
  516. DELETE /api/v1/users/account
  517. Payload:
  518. {
  519. "provider": "twitter",
  520. "uid": 581482342942
  521. }
  522. Response:
  523. {
  524. :message => 'ok'
  525. }
  526. Test:
  527. curl http://localhost/api/v1/users/account -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  528. =end
  529. def account_remove
  530. # provider + uid to remove
  531. raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
  532. raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
  533. Service::User::RemoveLinkedAccount.new(provider: params[:provider], uid: params[:uid], current_user:).execute
  534. render json: { message: 'ok' }, status: :ok
  535. end
  536. =begin
  537. Resource:
  538. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  539. Response:
  540. <IMAGE>
  541. Test:
  542. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  543. =end
  544. def image
  545. # Cache images in the browser.
  546. expires_in(1.year.from_now, must_revalidate: true)
  547. file = Avatar.get_by_hash(params[:hash])
  548. if file
  549. file_content_type = file.preferences['Content-Type'] || file.preferences['Mime-Type']
  550. return serve_default_image if ActiveStorage.content_types_allowed_inline.exclude?(file_content_type)
  551. send_data(
  552. file.content,
  553. filename: file.filename,
  554. type: file_content_type,
  555. disposition: 'inline'
  556. )
  557. return
  558. end
  559. serve_default_image
  560. end
  561. =begin
  562. Resource:
  563. POST /api/v1/users/avatar
  564. Payload:
  565. {
  566. "avatar_full": "base64 url",
  567. }
  568. Response:
  569. {
  570. message: 'ok'
  571. }
  572. Test:
  573. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  574. =end
  575. def avatar_new
  576. service = Service::Avatar::ImageValidate.new
  577. file_full = service.execute(image_data: params[:avatar_full])
  578. if file_full[:error].present?
  579. render json: { error: file_full[:message] }, status: :unprocessable_entity
  580. return
  581. end
  582. file_resize = service.execute(image_data: params[:avatar_resize])
  583. if file_resize[:error].present?
  584. render json: { error: file_resize[:message] }, status: :unprocessable_entity
  585. return
  586. end
  587. render json: { avatar: Service::Avatar::Add.new(current_user: current_user).execute(full_image: file_full, resize_image: file_resize) }, status: :ok
  588. end
  589. def avatar_set_default
  590. # get & validate image
  591. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  592. # set as default
  593. avatar = Avatar.set_default('User', current_user.id, params[:id])
  594. # update user link
  595. user = User.find(current_user.id)
  596. user.update!(image: avatar.store_hash)
  597. render json: {}, status: :ok
  598. end
  599. def avatar_destroy
  600. # get & validate image
  601. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  602. # remove avatar
  603. Avatar.remove_one('User', current_user.id, params[:id])
  604. # update user link
  605. avatar = Avatar.get_default('User', current_user.id)
  606. user = User.find(current_user.id)
  607. user.update!(image: avatar.store_hash)
  608. render json: {}, status: :ok
  609. end
  610. def avatar_list
  611. # list of avatars
  612. result = Avatar.list('User', current_user.id)
  613. render json: { avatars: result }, status: :ok
  614. end
  615. # @path [GET] /users/import_example
  616. #
  617. # @summary Download of example CSV file.
  618. # @notes The requester have 'admin.user' permissions to be able to download it.
  619. # @example curl -u #{login}:#{password} http://localhost:3000/api/v1/users/import_example
  620. #
  621. # @response_message 200 File download.
  622. # @response_message 403 Forbidden / Invalid session.
  623. def import_example
  624. send_data(
  625. User.csv_example,
  626. filename: 'user-example.csv',
  627. type: 'text/csv',
  628. disposition: 'attachment'
  629. )
  630. end
  631. # @path [POST] /users/import
  632. #
  633. # @summary Starts import.
  634. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  635. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  636. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  637. #
  638. # @response_message 201 Import started.
  639. # @response_message 403 Forbidden / Invalid session.
  640. def import_start
  641. string = params[:data]
  642. if string.blank? && params[:file].present?
  643. string = params[:file].read.force_encoding('utf-8')
  644. end
  645. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  646. result = User.csv_import(
  647. string: string,
  648. parse_params: {
  649. col_sep: params[:col_sep] || ',',
  650. },
  651. try: params[:try],
  652. delete: params[:delete],
  653. )
  654. render json: result, status: :ok
  655. end
  656. def two_factor_enabled_authentication_methods
  657. user = User.find(params[:id])
  658. render json: { methods: user.two_factor_enabled_authentication_methods }, status: :ok
  659. end
  660. private
  661. def password_login?
  662. return true if Setting.get('user_show_password_login')
  663. return true if Setting.where('name LIKE ? AND frontend = true', "#{SqlHelper.quote_like('auth_')}%")
  664. .map { |provider| provider.state_current['value'] }
  665. .all?(false)
  666. false
  667. end
  668. def clean_user_params
  669. User.param_cleanup(User.association_name_to_id_convert(params), true).merge(screen: 'create')
  670. end
  671. # @summary Creates a User record with the provided attribute values.
  672. # @notes For creating a user via agent interface
  673. #
  674. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  675. #
  676. # @response_message 200 [User] Created User record.
  677. # @response_message 403 Forbidden / Invalid session.
  678. def create_internal
  679. # permission check
  680. check_attributes_by_current_user_permission(params)
  681. user = User.new(clean_user_params)
  682. user.associations_from_param(params)
  683. user.save!
  684. if params[:invite].present?
  685. token = Token.create(action: 'PasswordReset', user_id: user.id)
  686. NotificationFactory::Mailer.notification(
  687. template: 'user_invite',
  688. user: user,
  689. objects: {
  690. token: token,
  691. user: user,
  692. current_user: current_user,
  693. }
  694. )
  695. end
  696. if response_expand?
  697. user = user.reload.attributes_with_association_names
  698. user.delete('password')
  699. render json: user, status: :created
  700. return
  701. end
  702. if response_full?
  703. result = {
  704. id: user.id,
  705. assets: user.assets({}),
  706. }
  707. render json: result, status: :created
  708. return
  709. end
  710. user = user.reload.attributes_with_association_ids
  711. user.delete('password')
  712. render json: user, status: :created
  713. end
  714. # @summary Creates a User record with the provided attribute values.
  715. # @notes For creating a user via public signup form
  716. #
  717. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  718. #
  719. # @response_message 200 [User] Created User record.
  720. # @response_message 403 Forbidden / Invalid session.
  721. def create_signup
  722. # check signup option only after admin account is created
  723. if !params[:signup]
  724. raise Exceptions::UnprocessableEntity, __("The required parameter 'signup' is missing.")
  725. end
  726. # only allow fixed fields
  727. # TODO: https://github.com/zammad/zammad/issues/3295
  728. new_params = clean_user_params.slice(:firstname, :lastname, :email, :password)
  729. # check if user already exists
  730. if new_params[:email].blank?
  731. raise Exceptions::UnprocessableEntity, __("The required attribute 'email' is missing.")
  732. end
  733. signup = Service::User::Deprecated::Signup.new(user_data: new_params)
  734. begin
  735. signup.execute
  736. rescue PasswordPolicy::Error => e
  737. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  738. return
  739. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  740. raise Exceptions::UnprocessableEntity, e.message
  741. end
  742. render json: { message: 'ok' }, status: :created
  743. end
  744. # @summary Creates a User record with the provided attribute values.
  745. # @notes For creating an administrator account when setting up the system
  746. #
  747. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  748. #
  749. # @response_message 200 [User] Created User record.
  750. # @response_message 403 Forbidden / Invalid session.
  751. def create_admin
  752. Service::User::AddFirstAdmin.new.execute(
  753. user_data: clean_user_params.slice(:firstname, :lastname, :email, :password),
  754. request: request,
  755. )
  756. render json: { message: 'ok' }, status: :created
  757. rescue PasswordPolicy::Error => e
  758. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  759. rescue Exceptions::MissingAttribute, Service::System::CheckSetup::SystemSetupError => e
  760. raise Exceptions::UnprocessableEntity, e.message
  761. end
  762. def serve_default_image
  763. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  764. send_data(
  765. Base64.decode64(image),
  766. filename: 'image.gif',
  767. type: 'image/gif',
  768. disposition: 'inline'
  769. )
  770. end
  771. end