users_controller.rb 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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. query = params[:query]
  196. if query.respond_to?(:permit!)
  197. query.permit!.to_h
  198. end
  199. query = params[:query] || params[:term]
  200. if query.respond_to?(:permit!)
  201. query = query.permit!.to_h
  202. end
  203. query_params = {
  204. query: query,
  205. limit: pagination.limit,
  206. offset: pagination.offset,
  207. sort_by: params[:sort_by],
  208. order_by: params[:order_by],
  209. current_user: current_user,
  210. }
  211. %i[ids role_ids group_ids permissions].each do |key|
  212. next if params[key].blank?
  213. query_params[key] = params[key]
  214. end
  215. # do query
  216. user_all = User.search(query_params)
  217. if response_expand?
  218. list = user_all.map(&:attributes_with_association_names)
  219. render json: list, status: :ok
  220. return
  221. end
  222. # build result list
  223. if params[:label] || params[:term]
  224. users = []
  225. user_all.each do |user|
  226. realname = user.fullname
  227. # improve realname, if possible
  228. if user.email.present? && realname != user.email
  229. begin
  230. realname = Channel::EmailBuild.recipient_line(realname, user.email)
  231. rescue Mail::Field::IncompleteParseError
  232. # mute if parsing of recipient_line was not successful / #5166
  233. end
  234. end
  235. a = if params[:term]
  236. { id: user.id, label: realname, value: user.email, inactive: !user.active }
  237. else
  238. { id: user.id, label: realname, value: realname }
  239. end
  240. users.push a
  241. end
  242. # return result
  243. render json: users
  244. return
  245. end
  246. if response_full?
  247. user_ids = []
  248. assets = {}
  249. user_all.each do |user|
  250. assets = user.assets(assets)
  251. user_ids.push user.id
  252. end
  253. # return result
  254. render json: {
  255. assets: assets,
  256. user_ids: user_ids.uniq,
  257. }
  258. return
  259. end
  260. list = user_all.map(&:attributes_with_association_ids)
  261. render json: list, status: :ok
  262. end
  263. # @path [GET] /users/history/{id}
  264. #
  265. # @tag History
  266. # @tag User
  267. #
  268. # @summary Returns the History records of a User record matching the given identifier.
  269. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  270. # get the History records of a User record.
  271. #
  272. # @parameter id(required) [Integer] The identifier matching the requested User record.
  273. #
  274. # @response_message 200 [History] The History records of the requested User record.
  275. # @response_message 403 Forbidden / Invalid session.
  276. def history
  277. # get user data
  278. user = User.find(params[:id])
  279. # get history of user
  280. render json: user.history_get(true)
  281. end
  282. # @path [PUT] /users/unlock/{id}
  283. #
  284. # @summary Unlocks the User record matching the identifier.
  285. # @notes The requester have 'admin.user' permissions to be able to unlock a user.
  286. #
  287. # @parameter id(required) [Integer] The identifier matching the requested User record.
  288. #
  289. # @response_message 200 Unlocked User record.
  290. # @response_message 403 Forbidden / Invalid session.
  291. def unlock
  292. user = User.find(params[:id])
  293. user.with_lock do
  294. user.update!(login_failed: 0)
  295. end
  296. render json: { message: 'ok' }, status: :ok
  297. end
  298. =begin
  299. Resource:
  300. POST /api/v1/users/email_verify
  301. Payload:
  302. {
  303. "token": "SoMeToKeN",
  304. }
  305. Response:
  306. {
  307. :message => 'ok'
  308. }
  309. Test:
  310. curl http://localhost/api/v1/users/email_verify -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"token": "SoMeToKeN"}'
  311. =end
  312. def email_verify
  313. raise Exceptions::UnprocessableEntity, __('No token!') if !params[:token]
  314. verify = Service::User::SignupVerify.new(token: params[:token], current_user: current_user)
  315. begin
  316. user = verify.execute
  317. rescue Service::CheckFeatureEnabled::FeatureDisabledError, Service::User::SignupVerify::InvalidTokenError => e
  318. raise Exceptions::UnprocessableEntity, e.message
  319. end
  320. current_user_set(user) if user
  321. msg = user ? { message: 'ok', user_email: user.email } : { message: 'failed' }
  322. render json: msg, status: :ok
  323. end
  324. =begin
  325. Resource:
  326. POST /api/v1/users/email_verify_send
  327. Payload:
  328. {
  329. "email": "some_email@example.com"
  330. }
  331. Response:
  332. {
  333. :message => 'ok'
  334. }
  335. Test:
  336. 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"}'
  337. =end
  338. def email_verify_send
  339. raise Exceptions::UnprocessableEntity, __('No email!') if !params[:email]
  340. signup = Service::User::Deprecated::Signup.new(user_data: { email: params[:email] }, resend: true)
  341. begin
  342. signup.execute
  343. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  344. raise Exceptions::UnprocessableEntity, e.message
  345. rescue Service::User::Signup::TokenGenerationError
  346. render json: { message: 'failed' }, status: :ok
  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/admin_login
  354. Payload:
  355. {
  356. "username": "some user name"
  357. }
  358. Response:
  359. {
  360. :message => 'ok'
  361. }
  362. Test:
  363. curl http://localhost/api/v1/users/admin_login -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  364. =end
  365. def admin_password_auth_send
  366. raise Exceptions::UnprocessableEntity, 'username param needed!' if params[:username].blank?
  367. send = Service::Auth::Deprecated::SendAdminToken.new(login: params[:username])
  368. begin
  369. send.execute
  370. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  371. raise Exceptions::UnprocessableEntity, e.message
  372. rescue Service::Auth::Deprecated::SendAdminToken::TokenError, Service::Auth::Deprecated::SendAdminToken::EmailError
  373. render json: { message: 'failed' }, status: :ok
  374. return
  375. end
  376. render json: { message: 'ok' }, status: :ok
  377. end
  378. def admin_password_auth_verify
  379. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  380. verify = Service::Auth::VerifyAdminToken.new(token: params[:token])
  381. user = begin
  382. verify.execute
  383. rescue => e
  384. raise Exceptions::UnprocessableEntity, e.message
  385. end
  386. msg = user ? { message: 'ok', user_login: user.login } : { message: 'failed' }
  387. render json: msg, status: :ok
  388. end
  389. =begin
  390. Resource:
  391. POST /api/v1/users/password_reset
  392. Payload:
  393. {
  394. "username": "some user name"
  395. }
  396. Response:
  397. {
  398. :message => 'ok'
  399. }
  400. Test:
  401. curl http://localhost/api/v1/users/password_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  402. =end
  403. def password_reset_send
  404. raise Exceptions::UnprocessableEntity, 'username param needed!' if params[:username].blank?
  405. send = Service::User::PasswordReset::Deprecated::Send.new(username: params[:username])
  406. begin
  407. send.execute
  408. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  409. raise Exceptions::UnprocessableEntity, e.message
  410. rescue Service::User::PasswordReset::Send::EmailError
  411. render json: { message: 'failed' }, status: :ok
  412. return
  413. end
  414. # Result is always positive to avoid leaking of existing user accounts.
  415. render json: { message: 'ok' }, status: :ok
  416. end
  417. =begin
  418. Resource:
  419. POST /api/v1/users/password_reset_verify
  420. Payload:
  421. {
  422. "token": "SoMeToKeN",
  423. "password": "new_pw"
  424. }
  425. Response:
  426. {
  427. :message => 'ok'
  428. }
  429. Test:
  430. 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"}'
  431. =end
  432. def password_reset_verify
  433. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  434. # If no password is given, verify token only.
  435. if params[:password].blank?
  436. verify = Service::User::PasswordReset::Verify.new(token: params[:token])
  437. begin
  438. user = verify.execute
  439. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  440. raise Exceptions::UnprocessableEntity, e.message
  441. rescue Service::User::PasswordReset::Verify::InvalidTokenError
  442. render json: { message: 'failed' }, status: :ok
  443. return
  444. end
  445. render json: { message: 'ok', user_login: user.login }, status: :ok
  446. return
  447. end
  448. update = Service::User::PasswordReset::Update.new(token: params[:token], password: params[:password])
  449. begin
  450. user = update.execute
  451. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  452. raise Exceptions::UnprocessableEntity, e.message
  453. rescue Service::User::PasswordReset::Update::InvalidTokenError, Service::User::PasswordReset::Update::EmailError
  454. render json: { message: 'failed' }, status: :ok
  455. return
  456. rescue PasswordPolicy::Error => e
  457. render json: { message: 'failed', notice: e.metadata }, status: :ok
  458. return
  459. end
  460. render json: { message: 'ok', user_login: user.login }, status: :ok
  461. end
  462. =begin
  463. Resource:
  464. POST /api/v1/users/password_change
  465. Payload:
  466. {
  467. "password_old": "old_pw",
  468. "password_new": "new_pw"
  469. }
  470. Response:
  471. {
  472. :message => 'ok'
  473. }
  474. Test:
  475. 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"}'
  476. =end
  477. def password_change
  478. # check old password
  479. if !params[:password_old] || !PasswordPolicy::MaxLength.valid?(params[:password_old])
  480. render json: { message: 'failed', notice: [__('Please provide your current password.')] }, status: :unprocessable_entity
  481. return
  482. end
  483. # set new password
  484. if !params[:password_new]
  485. render json: { message: 'failed', notice: [__('Please provide your new password.')] }, status: :unprocessable_entity
  486. return
  487. end
  488. begin
  489. Service::User::ChangePassword.new(
  490. user: current_user,
  491. current_password: params[:password_old],
  492. new_password: params[:password_new]
  493. ).execute
  494. rescue PasswordPolicy::Error => e
  495. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  496. return
  497. rescue PasswordHash::Error
  498. render json: { message: 'failed', notice: [__('The current password you provided is incorrect.')] }, status: :unprocessable_entity
  499. return
  500. end
  501. render json: { message: 'ok', user_login: current_user.login }, status: :ok
  502. end
  503. def password_check
  504. raise Exceptions::UnprocessableEntity, __("The required parameter 'password' is missing.") if params[:password].blank?
  505. password_check = Service::User::PasswordCheck.new(user: current_user, password: params[:password])
  506. render json: { success: password_check.execute }, status: :ok
  507. end
  508. =begin
  509. Resource:
  510. PUT /api/v1/users/preferences
  511. Payload:
  512. {
  513. "language": "de",
  514. "notification": true
  515. }
  516. Response:
  517. {
  518. :message => 'ok'
  519. }
  520. Test:
  521. curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  522. =end
  523. def preferences
  524. preferences_params = params.except(:controller, :action)
  525. if preferences_params.present?
  526. user = User.find(current_user.id)
  527. user.with_lock do
  528. preferences_params.permit!.to_h.each do |key, value|
  529. user.preferences[key.to_sym] = value
  530. end
  531. user.save!
  532. end
  533. end
  534. render json: { message: 'ok' }, status: :ok
  535. end
  536. =begin
  537. Resource:
  538. POST /api/v1/users/preferences_reset
  539. Response:
  540. {
  541. :message => 'ok'
  542. }
  543. Test:
  544. curl http://localhost/api/v1/users/preferences_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST'
  545. =end
  546. def preferences_notifications_reset
  547. User.reset_notifications_preferences!(current_user)
  548. render json: { message: 'ok' }, status: :ok
  549. end
  550. =begin
  551. Resource:
  552. PUT /api/v1/users/out_of_office
  553. Payload:
  554. {
  555. "out_of_office": true,
  556. "out_of_office_start_at": true,
  557. "out_of_office_end_at": true,
  558. "out_of_office_replacement_id": 123,
  559. "out_of_office_text": 'honeymoon'
  560. }
  561. Response:
  562. {
  563. :message => 'ok'
  564. }
  565. Test:
  566. 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}'
  567. =end
  568. def out_of_office
  569. user = User.find(current_user.id)
  570. Service::User::OutOfOffice
  571. .new(user,
  572. enabled: params[:out_of_office],
  573. start_at: params[:out_of_office_start_at],
  574. end_at: params[:out_of_office_end_at],
  575. replacement: User.find_by(id: params[:out_of_office_replacement_id]),
  576. text: params[:out_of_office_text])
  577. .execute
  578. render json: { message: 'ok' }, status: :ok
  579. end
  580. =begin
  581. Resource:
  582. DELETE /api/v1/users/account
  583. Payload:
  584. {
  585. "provider": "twitter",
  586. "uid": 581482342942
  587. }
  588. Response:
  589. {
  590. :message => 'ok'
  591. }
  592. Test:
  593. curl http://localhost/api/v1/users/account -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  594. =end
  595. def account_remove
  596. # provider + uid to remove
  597. raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
  598. raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
  599. Service::User::RemoveLinkedAccount.new(provider: params[:provider], uid: params[:uid], current_user:).execute
  600. render json: { message: 'ok' }, status: :ok
  601. end
  602. =begin
  603. Resource:
  604. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  605. Response:
  606. <IMAGE>
  607. Test:
  608. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  609. =end
  610. def image
  611. # Cache images in the browser.
  612. expires_in(1.year.from_now, must_revalidate: true)
  613. file = Avatar.get_by_hash(params[:hash])
  614. if file
  615. file_content_type = file.preferences['Content-Type'] || file.preferences['Mime-Type']
  616. return serve_default_image if ActiveStorage.content_types_allowed_inline.exclude?(file_content_type)
  617. send_data(
  618. file.content,
  619. filename: file.filename,
  620. type: file_content_type,
  621. disposition: 'inline'
  622. )
  623. return
  624. end
  625. serve_default_image
  626. end
  627. =begin
  628. Resource:
  629. POST /api/v1/users/avatar
  630. Payload:
  631. {
  632. "avatar_full": "base64 url",
  633. }
  634. Response:
  635. {
  636. message: 'ok'
  637. }
  638. Test:
  639. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  640. =end
  641. def avatar_new
  642. service = Service::Avatar::ImageValidate.new
  643. file_full = service.execute(image_data: params[:avatar_full])
  644. if file_full[:error].present?
  645. render json: { error: file_full[:message] }, status: :unprocessable_entity
  646. return
  647. end
  648. file_resize = service.execute(image_data: params[:avatar_resize])
  649. if file_resize[:error].present?
  650. render json: { error: file_resize[:message] }, status: :unprocessable_entity
  651. return
  652. end
  653. render json: { avatar: Service::Avatar::Add.new(current_user: current_user).execute(full_image: file_full, resize_image: file_resize) }, status: :ok
  654. end
  655. def avatar_set_default
  656. # get & validate image
  657. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  658. # set as default
  659. avatar = Avatar.set_default('User', current_user.id, params[:id])
  660. # update user link
  661. user = User.find(current_user.id)
  662. user.update!(image: avatar.store_hash)
  663. render json: {}, status: :ok
  664. end
  665. def avatar_destroy
  666. # get & validate image
  667. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  668. # remove avatar
  669. Avatar.remove_one('User', current_user.id, params[:id])
  670. # update user link
  671. avatar = Avatar.get_default('User', current_user.id)
  672. user = User.find(current_user.id)
  673. user.update!(image: avatar.store_hash)
  674. render json: {}, status: :ok
  675. end
  676. def avatar_list
  677. # list of avatars
  678. result = Avatar.list('User', current_user.id)
  679. render json: { avatars: result }, status: :ok
  680. end
  681. # @path [GET] /users/import_example
  682. #
  683. # @summary Download of example CSV file.
  684. # @notes The requester have 'admin.user' permissions to be able to download it.
  685. # @example curl -u #{login}:#{password} http://localhost:3000/api/v1/users/import_example
  686. #
  687. # @response_message 200 File download.
  688. # @response_message 403 Forbidden / Invalid session.
  689. def import_example
  690. send_data(
  691. User.csv_example,
  692. filename: 'user-example.csv',
  693. type: 'text/csv',
  694. disposition: 'attachment'
  695. )
  696. end
  697. # @path [POST] /users/import
  698. #
  699. # @summary Starts import.
  700. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  701. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  702. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  703. #
  704. # @response_message 201 Import started.
  705. # @response_message 403 Forbidden / Invalid session.
  706. def import_start
  707. string = params[:data]
  708. if string.blank? && params[:file].present?
  709. string = params[:file].read.force_encoding('utf-8')
  710. end
  711. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  712. result = User.csv_import(
  713. string: string,
  714. parse_params: {
  715. col_sep: params[:col_sep] || ',',
  716. },
  717. try: params[:try],
  718. delete: params[:delete],
  719. )
  720. render json: result, status: :ok
  721. end
  722. def two_factor_enabled_authentication_methods
  723. user = User.find(params[:id])
  724. render json: { methods: user.two_factor_enabled_authentication_methods }, status: :ok
  725. end
  726. private
  727. def password_login?
  728. return true if Setting.get('user_show_password_login')
  729. return true if Setting.where('name LIKE ? AND frontend = true', "#{SqlHelper.quote_like('auth_')}%")
  730. .map { |provider| provider.state_current['value'] }
  731. .all?(false)
  732. false
  733. end
  734. def clean_user_params
  735. User.param_cleanup(User.association_name_to_id_convert(params), true).merge(screen: 'create')
  736. end
  737. # @summary Creates a User record with the provided attribute values.
  738. # @notes For creating a user via agent interface
  739. #
  740. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  741. #
  742. # @response_message 200 [User] Created User record.
  743. # @response_message 403 Forbidden / Invalid session.
  744. def create_internal
  745. # permission check
  746. check_attributes_by_current_user_permission(params)
  747. user = User.new(clean_user_params)
  748. user.associations_from_param(params)
  749. user.save!
  750. if params[:invite].present?
  751. token = Token.create(action: 'PasswordReset', user_id: user.id)
  752. NotificationFactory::Mailer.notification(
  753. template: 'user_invite',
  754. user: user,
  755. objects: {
  756. token: token,
  757. user: user,
  758. current_user: current_user,
  759. }
  760. )
  761. end
  762. if response_expand?
  763. user = user.reload.attributes_with_association_names
  764. user.delete('password')
  765. render json: user, status: :created
  766. return
  767. end
  768. if response_full?
  769. result = {
  770. id: user.id,
  771. assets: user.assets({}),
  772. }
  773. render json: result, status: :created
  774. return
  775. end
  776. user = user.reload.attributes_with_association_ids
  777. user.delete('password')
  778. render json: user, status: :created
  779. end
  780. # @summary Creates a User record with the provided attribute values.
  781. # @notes For creating a user via public signup form
  782. #
  783. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  784. #
  785. # @response_message 200 [User] Created User record.
  786. # @response_message 403 Forbidden / Invalid session.
  787. def create_signup
  788. # check signup option only after admin account is created
  789. if !params[:signup]
  790. raise Exceptions::UnprocessableEntity, __("The required parameter 'signup' is missing.")
  791. end
  792. # only allow fixed fields
  793. # TODO: https://github.com/zammad/zammad/issues/3295
  794. new_params = clean_user_params.slice(:firstname, :lastname, :email, :password)
  795. # check if user already exists
  796. if new_params[:email].blank?
  797. raise Exceptions::UnprocessableEntity, __("The required attribute 'email' is missing.")
  798. end
  799. signup = Service::User::Deprecated::Signup.new(user_data: new_params)
  800. begin
  801. signup.execute
  802. rescue PasswordPolicy::Error => e
  803. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  804. return
  805. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  806. raise Exceptions::UnprocessableEntity, e.message
  807. end
  808. render json: { message: 'ok' }, status: :created
  809. end
  810. # @summary Creates a User record with the provided attribute values.
  811. # @notes For creating an administrator account when setting up the system
  812. #
  813. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  814. #
  815. # @response_message 200 [User] Created User record.
  816. # @response_message 403 Forbidden / Invalid session.
  817. def create_admin
  818. Service::User::AddFirstAdmin.new.execute(
  819. user_data: clean_user_params.slice(:firstname, :lastname, :email, :password),
  820. request: request,
  821. )
  822. render json: { message: 'ok' }, status: :created
  823. rescue PasswordPolicy::Error => e
  824. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  825. rescue Exceptions::MissingAttribute, Service::System::CheckSetup::SystemSetupError => e
  826. raise Exceptions::UnprocessableEntity, e.message
  827. end
  828. def serve_default_image
  829. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  830. send_data(
  831. Base64.decode64(image),
  832. filename: 'image.gif',
  833. type: 'image/gif',
  834. disposition: 'inline'
  835. )
  836. end
  837. end