users_controller.rb 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. # Copyright (C) 2012-2025 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. if (avatar = Avatar.get_default('User', current_user.id))
  672. user = User.find(current_user.id)
  673. user.update!(image: avatar.store_hash)
  674. end
  675. render json: {}, status: :ok
  676. end
  677. def avatar_list
  678. # list of avatars
  679. result = Avatar.list('User', current_user.id)
  680. render json: { avatars: result }, status: :ok
  681. end
  682. # @path [GET] /users/import_example
  683. #
  684. # @summary Download of example CSV file.
  685. # @notes The requester have 'admin.user' permissions to be able to download it.
  686. # @example curl -u #{login}:#{password} http://localhost:3000/api/v1/users/import_example
  687. #
  688. # @response_message 200 File download.
  689. # @response_message 403 Forbidden / Invalid session.
  690. def import_example
  691. send_data(
  692. User.csv_example,
  693. filename: 'user-example.csv',
  694. type: 'text/csv',
  695. disposition: 'attachment'
  696. )
  697. end
  698. # @path [POST] /users/import
  699. #
  700. # @summary Starts import.
  701. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  702. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  703. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  704. #
  705. # @response_message 201 Import started.
  706. # @response_message 403 Forbidden / Invalid session.
  707. def import_start
  708. string = params[:data]
  709. if string.blank? && params[:file].present?
  710. string = params[:file].read.force_encoding('utf-8')
  711. end
  712. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  713. result = User.csv_import(
  714. string: string,
  715. parse_params: {
  716. col_sep: params[:col_sep] || ',',
  717. },
  718. try: params[:try],
  719. delete: params[:delete],
  720. )
  721. render json: result, status: :ok
  722. end
  723. def two_factor_enabled_authentication_methods
  724. user = User.find(params[:id])
  725. render json: { methods: user.two_factor_enabled_authentication_methods }, status: :ok
  726. end
  727. private
  728. def password_login?
  729. return true if Setting.get('user_show_password_login')
  730. return true if Setting.where('name LIKE ? AND frontend = true', "#{SqlHelper.quote_like('auth_')}%")
  731. .map { |provider| provider.state_current['value'] }
  732. .all?(false)
  733. false
  734. end
  735. def clean_user_params
  736. User.param_cleanup(User.association_name_to_id_convert(params), true).merge(screen: 'create')
  737. end
  738. # @summary Creates a User record with the provided attribute values.
  739. # @notes For creating a user via agent interface
  740. #
  741. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  742. #
  743. # @response_message 200 [User] Created User record.
  744. # @response_message 403 Forbidden / Invalid session.
  745. def create_internal
  746. # permission check
  747. check_attributes_by_current_user_permission(params)
  748. user = User.new(clean_user_params)
  749. user.associations_from_param(params)
  750. user.save!
  751. if params[:invite].present?
  752. token = Token.create(action: 'PasswordReset', user_id: user.id)
  753. NotificationFactory::Mailer.notification(
  754. template: 'user_invite',
  755. user: user,
  756. objects: {
  757. token: token,
  758. user: user,
  759. current_user: current_user,
  760. }
  761. )
  762. end
  763. if response_expand?
  764. user = user.reload.attributes_with_association_names
  765. user.delete('password')
  766. render json: user, status: :created
  767. return
  768. end
  769. if response_full?
  770. result = {
  771. id: user.id,
  772. assets: user.assets({}),
  773. }
  774. render json: result, status: :created
  775. return
  776. end
  777. user = user.reload.attributes_with_association_ids
  778. user.delete('password')
  779. render json: user, status: :created
  780. end
  781. # @summary Creates a User record with the provided attribute values.
  782. # @notes For creating a user via public signup form
  783. #
  784. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  785. #
  786. # @response_message 200 [User] Created User record.
  787. # @response_message 403 Forbidden / Invalid session.
  788. def create_signup
  789. # check signup option only after admin account is created
  790. if !params[:signup]
  791. raise Exceptions::UnprocessableEntity, __("The required parameter 'signup' is missing.")
  792. end
  793. # only allow fixed fields
  794. # TODO: https://github.com/zammad/zammad/issues/3295
  795. new_params = clean_user_params.slice(:firstname, :lastname, :email, :password)
  796. # check if user already exists
  797. if new_params[:email].blank?
  798. raise Exceptions::UnprocessableEntity, __("The required attribute 'email' is missing.")
  799. end
  800. signup = Service::User::Deprecated::Signup.new(user_data: new_params)
  801. begin
  802. signup.execute
  803. rescue PasswordPolicy::Error => e
  804. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  805. return
  806. rescue Service::CheckFeatureEnabled::FeatureDisabledError => e
  807. raise Exceptions::UnprocessableEntity, e.message
  808. end
  809. render json: { message: 'ok' }, status: :created
  810. end
  811. # @summary Creates a User record with the provided attribute values.
  812. # @notes For creating an administrator account when setting up the system
  813. #
  814. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  815. #
  816. # @response_message 200 [User] Created User record.
  817. # @response_message 403 Forbidden / Invalid session.
  818. def create_admin
  819. Service::User::AddFirstAdmin.new.execute(
  820. user_data: clean_user_params.slice(:firstname, :lastname, :email, :password),
  821. request: request,
  822. )
  823. render json: { message: 'ok' }, status: :created
  824. rescue PasswordPolicy::Error => e
  825. render json: { message: 'failed', notice: e.metadata }, status: :unprocessable_entity
  826. rescue Exceptions::MissingAttribute, Service::System::CheckSetup::SystemSetupError => e
  827. raise Exceptions::UnprocessableEntity, e.message
  828. end
  829. def serve_default_image
  830. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  831. send_data(
  832. Base64.decode64(image),
  833. filename: 'image.gif',
  834. type: 'image/gif',
  835. disposition: 'inline'
  836. )
  837. end
  838. end