users_controller.rb 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. # Copyright (C) 2012-2023 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 = []
  21. users.each do |user|
  22. list.push user.attributes_with_association_names
  23. end
  24. render json: list, status: :ok
  25. return
  26. end
  27. if response_full?
  28. assets = {}
  29. item_ids = []
  30. users.each do |item|
  31. item_ids.push item.id
  32. assets = item.assets(assets)
  33. end
  34. render json: {
  35. record_ids: item_ids,
  36. assets: assets,
  37. }, status: :ok
  38. return
  39. end
  40. users_all = []
  41. users.each do |user|
  42. users_all.push User.lookup(id: user.id).attributes_with_association_ids
  43. end
  44. render json: users_all, status: :ok
  45. end
  46. # @path [GET] /users/{id}
  47. #
  48. # @summary Returns the User record with the requested identifier.
  49. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  50. # access all User records. If the requester is in the
  51. # role 'Customer' just the own User record is accessable.
  52. #
  53. # @parameter id(required) [Integer] The identifier matching the requested User.
  54. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  55. #
  56. # @response_message 200 [User] User record matching the requested identifier.
  57. # @response_message 403 Forbidden / Invalid session.
  58. def show
  59. user = User.find(params[:id])
  60. authorize!(user)
  61. if response_expand?
  62. result = user.attributes_with_association_names
  63. result.delete('password')
  64. render json: result
  65. return
  66. end
  67. if response_full?
  68. result = {
  69. id: user.id,
  70. assets: user.assets({}),
  71. }
  72. render json: result
  73. return
  74. end
  75. result = user.attributes_with_association_ids
  76. result.delete('password')
  77. render json: result
  78. end
  79. # @path [POST] /users
  80. #
  81. # @summary processes requests as CRUD-like record creation, admin creation or user signup depending on circumstances
  82. # @see #create_internal #create_admin #create_signup
  83. def create
  84. if current_user
  85. create_internal
  86. elsif params[:signup]
  87. create_signup
  88. else
  89. create_admin
  90. end
  91. end
  92. # @path [PUT] /users/{id}
  93. #
  94. # @summary Updates the User record matching the identifier with the provided attribute values.
  95. # @notes TODO.
  96. #
  97. # @parameter id(required) [Integer] The identifier matching the requested User record.
  98. # @parameter User(required,body) [User] The attribute value structure needed to update a User record.
  99. #
  100. # @response_message 200 [User] Updated User record.
  101. # @response_message 403 Forbidden / Invalid session.
  102. def update
  103. user = User.find(params[:id])
  104. authorize!(user)
  105. # permission check
  106. check_attributes_by_current_user_permission(params)
  107. user.with_lock do
  108. clean_params = User.association_name_to_id_convert(params)
  109. clean_params = User.param_cleanup(clean_params, true)
  110. clean_params[:screen] = 'edit'
  111. # presence and permissions were checked via `check_attributes_by_current_user_permission`
  112. privileged_attributes = params.slice(:role_ids, :roles, :group_ids, :groups, :organization_ids, :organizations)
  113. if privileged_attributes.present?
  114. user.associations_from_param(privileged_attributes)
  115. end
  116. user.update!(clean_params)
  117. end
  118. if response_expand?
  119. user = user.reload.attributes_with_association_names
  120. user.delete('password')
  121. render json: user, status: :ok
  122. return
  123. end
  124. if response_full?
  125. result = {
  126. id: user.id,
  127. assets: user.assets({}),
  128. }
  129. render json: result, status: :ok
  130. return
  131. end
  132. user = user.reload.attributes_with_association_ids
  133. user.delete('password')
  134. render json: user, status: :ok
  135. end
  136. # @path [DELETE] /users/{id}
  137. #
  138. # @summary Deletes the User record matching the given identifier.
  139. # @notes The requester has to be in the role 'Admin' to be able to delete a User record.
  140. #
  141. # @parameter id(required) [User] The identifier matching the requested User record.
  142. #
  143. # @response_message 200 User successfully deleted.
  144. # @response_message 403 Forbidden / Invalid session.
  145. def destroy
  146. user = User.find(params[:id])
  147. authorize!(user)
  148. model_references_check(User, params)
  149. model_destroy_render(User, params)
  150. end
  151. # @path [GET] /users/me
  152. #
  153. # @summary Returns the User record of current user.
  154. # @notes The requester needs to have a valid authentication.
  155. #
  156. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  157. #
  158. # @response_message 200 [User] User record matching the requested identifier.
  159. # @response_message 403 Forbidden / Invalid session.
  160. def me
  161. if response_expand?
  162. user = current_user.attributes_with_association_names
  163. user.delete('password')
  164. render json: user, status: :ok
  165. return
  166. end
  167. if response_full?
  168. full = User.full(current_user.id)
  169. render json: full
  170. return
  171. end
  172. user = current_user.attributes_with_association_ids
  173. user.delete('password')
  174. render json: user
  175. end
  176. # @path [GET] /users/search
  177. #
  178. # @tag Search
  179. # @tag User
  180. #
  181. # @summary Searches the User matching the given expression(s).
  182. # @notes TODO: It's possible to use the SOLR search syntax.
  183. # The requester has to be in the role 'Admin' or 'Agent' to
  184. # be able to search for User records.
  185. #
  186. # @parameter query [String] The search query.
  187. # @parameter limit [Integer] The limit of search results.
  188. # @parameter ids(multi) [Array<Integer>] A list of User IDs which should be returned
  189. # @parameter role_ids(multi) [Array<Integer>] A list of Role identifiers to which the Users have to be allocated to.
  190. # @parameter group_ids(multi) [Hash<String=>Integer,Array<Integer>>] A list of Group identifiers to which the Users have to be allocated to.
  191. # @parameter permissions(multi) [Array<String>] A list of Permission identifiers to which the Users have to be allocated to.
  192. # @parameter full [Boolean] Defines if the result should be
  193. # true: { user_ids => [1,2,...], assets => {...} }
  194. # or false: [{:id => user.id, :label => "firstname lastname <email>", :value => "firstname lastname <email>"},...].
  195. #
  196. # @response_message 200 [Array<User>] A list of User records matching the search term.
  197. # @response_message 403 Forbidden / Invalid session.
  198. def search
  199. query = params[:query]
  200. if query.respond_to?(:permit!)
  201. query.permit!.to_h
  202. end
  203. query = params[:query] || params[:term]
  204. if query.respond_to?(:permit!)
  205. query = query.permit!.to_h
  206. end
  207. query_params = {
  208. query: query,
  209. limit: pagination.limit,
  210. offset: pagination.offset,
  211. sort_by: params[:sort_by],
  212. order_by: params[:order_by],
  213. current_user: current_user,
  214. }
  215. %i[ids role_ids group_ids permissions].each do |key|
  216. next if params[key].blank?
  217. query_params[key] = params[key]
  218. end
  219. # do query
  220. user_all = User.search(query_params)
  221. if response_expand?
  222. list = []
  223. user_all.each do |user|
  224. list.push user.attributes_with_association_names
  225. end
  226. render json: list, status: :ok
  227. return
  228. end
  229. # build result list
  230. if params[:label] || params[:term]
  231. users = []
  232. user_all.each do |user|
  233. realname = user.fullname
  234. if user.email.present? && realname != user.email
  235. realname = Channel::EmailBuild.recipient_line realname, user.email
  236. end
  237. a = if params[:term]
  238. { id: user.id, label: realname, value: user.email, inactive: !user.active }
  239. else
  240. { id: user.id, label: realname, value: realname }
  241. end
  242. users.push a
  243. end
  244. # return result
  245. render json: users
  246. return
  247. end
  248. if response_full?
  249. user_ids = []
  250. assets = {}
  251. user_all.each do |user|
  252. assets = user.assets(assets)
  253. user_ids.push user.id
  254. end
  255. # return result
  256. render json: {
  257. assets: assets,
  258. user_ids: user_ids.uniq,
  259. }
  260. return
  261. end
  262. list = []
  263. user_all.each do |user|
  264. list.push user.attributes_with_association_ids
  265. end
  266. render json: list, status: :ok
  267. end
  268. # @path [GET] /users/history/{id}
  269. #
  270. # @tag History
  271. # @tag User
  272. #
  273. # @summary Returns the History records of a User record matching the given identifier.
  274. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  275. # get the History records of a User record.
  276. #
  277. # @parameter id(required) [Integer] The identifier matching the requested User record.
  278. #
  279. # @response_message 200 [History] The History records of the requested User record.
  280. # @response_message 403 Forbidden / Invalid session.
  281. def history
  282. # get user data
  283. user = User.find(params[:id])
  284. # get history of user
  285. render json: user.history_get(true)
  286. end
  287. # @path [PUT] /users/unlock/{id}
  288. #
  289. # @summary Unlocks the User record matching the identifier.
  290. # @notes The requester have 'admin.user' permissions to be able to unlock a user.
  291. #
  292. # @parameter id(required) [Integer] The identifier matching the requested User record.
  293. #
  294. # @response_message 200 Unlocked User record.
  295. # @response_message 403 Forbidden / Invalid session.
  296. def unlock
  297. user = User.find(params[:id])
  298. user.with_lock do
  299. user.update!(login_failed: 0)
  300. end
  301. render json: { message: 'ok' }, status: :ok
  302. end
  303. =begin
  304. Resource:
  305. POST /api/v1/users/email_verify
  306. Payload:
  307. {
  308. "token": "SoMeToKeN",
  309. }
  310. Response:
  311. {
  312. :message => 'ok'
  313. }
  314. Test:
  315. curl http://localhost/api/v1/users/email_verify -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"token": "SoMeToKeN"}'
  316. =end
  317. def email_verify
  318. raise Exceptions::UnprocessableEntity, __('No token!') if !params[:token]
  319. user = User.signup_verify_via_token(params[:token], current_user)
  320. raise Exceptions::UnprocessableEntity, __('The provided token is invalid.') if !user
  321. current_user_set(user)
  322. render json: { message: 'ok', user_email: user.email }, 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. user = User.find_by(email: params[:email].downcase)
  341. if !user || user.verified == true
  342. # result is always positive to avoid leaking of existing user accounts
  343. render json: { message: 'ok' }, status: :ok
  344. return
  345. end
  346. Token.create(action: 'Signup', user_id: user.id)
  347. result = User.signup_new_token(user)
  348. if result && result[:token]
  349. user = result[:user]
  350. NotificationFactory::Mailer.notification(
  351. template: 'signup',
  352. user: user,
  353. objects: result
  354. )
  355. # token sent to user, send ok to browser
  356. render json: { message: 'ok' }, status: :ok
  357. return
  358. end
  359. # unable to generate token
  360. render json: { message: 'failed' }, status: :ok
  361. end
  362. =begin
  363. Resource:
  364. POST /api/v1/users/admin_login
  365. Payload:
  366. {
  367. "username": "some user name"
  368. }
  369. Response:
  370. {
  371. :message => 'ok'
  372. }
  373. Test:
  374. curl http://localhost/api/v1/users/admin_login -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  375. =end
  376. def admin_password_auth_send
  377. # check if feature is enabled
  378. raise Exceptions::UnprocessableEntity, __('Feature not enabled!') if password_login?
  379. raise Exceptions::UnprocessableEntity, 'username param needed!' if params[:username].blank?
  380. result = User.admin_password_auth_new_token(params[:username])
  381. if result && result[:token]
  382. # unable to send email
  383. if !result[:user] || result[:user].email.blank?
  384. render json: { message: 'failed' }, status: :ok
  385. return
  386. end
  387. # send password reset emails
  388. NotificationFactory::Mailer.notification(
  389. template: 'admin_password_auth',
  390. user: result[:user],
  391. objects: result
  392. )
  393. end
  394. # result is always positive to avoid leaking of existing user accounts
  395. render json: { message: 'ok' }, status: :ok
  396. end
  397. def admin_password_auth_verify
  398. # check if feature is enabled
  399. raise Exceptions::UnprocessableEntity, __('Feature not enabled!') if password_login?
  400. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  401. user = User.admin_password_auth_via_token(params[:token])
  402. if !user
  403. render json: { message: 'failed' }, status: :ok
  404. return
  405. end
  406. # result is always positive to avoid leaking of existing user accounts
  407. render json: { message: 'ok', user_login: user.login }, status: :ok
  408. end
  409. =begin
  410. Resource:
  411. POST /api/v1/users/password_reset
  412. Payload:
  413. {
  414. "username": "some user name"
  415. }
  416. Response:
  417. {
  418. :message => 'ok'
  419. }
  420. Test:
  421. curl http://localhost/api/v1/users/password_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  422. =end
  423. def password_reset_send
  424. # check if feature is enabled
  425. raise Exceptions::UnprocessableEntity, __('Feature not enabled!') if !Setting.get('user_lost_password')
  426. result = User.password_reset_new_token(params[:username])
  427. if result && result[:token]
  428. # unable to send email
  429. if !result[:user] || result[:user].email.blank?
  430. render json: { message: 'failed' }, status: :ok
  431. return
  432. end
  433. # send password reset emails
  434. NotificationFactory::Mailer.notification(
  435. template: 'password_reset',
  436. user: result[:user],
  437. objects: result
  438. )
  439. end
  440. # result is always positive to avoid leaking of existing user accounts
  441. render json: { message: 'ok' }, status: :ok
  442. end
  443. =begin
  444. Resource:
  445. POST /api/v1/users/password_reset_verify
  446. Payload:
  447. {
  448. "token": "SoMeToKeN",
  449. "password": "new_password"
  450. }
  451. Response:
  452. {
  453. :message => 'ok'
  454. }
  455. Test:
  456. 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_password"}'
  457. =end
  458. def password_reset_verify
  459. # check if feature is enabled
  460. raise Exceptions::UnprocessableEntity, __('Feature not enabled!') if !Setting.get('user_lost_password')
  461. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  462. # if no password is given, verify token only
  463. if params[:password].blank?
  464. user = User.by_reset_token(params[:token])
  465. if user
  466. render json: { message: 'ok', user_login: user.login }, status: :ok
  467. return
  468. end
  469. render json: { message: 'failed' }, status: :ok
  470. return
  471. end
  472. result = PasswordPolicy.new(params[:password])
  473. if !result.valid?
  474. render json: { message: 'failed', notice: result.error }, status: :ok
  475. return
  476. end
  477. # set new password with token
  478. user = User.password_reset_via_token(params[:token], params[:password])
  479. # send mail
  480. if !user || user.email.blank?
  481. render json: { message: 'failed' }, status: :ok
  482. return
  483. end
  484. NotificationFactory::Mailer.notification(
  485. template: 'password_change',
  486. user: user,
  487. objects: {
  488. user: user,
  489. current_user: current_user,
  490. }
  491. )
  492. render json: { message: 'ok', user_login: user.login }, status: :ok
  493. end
  494. =begin
  495. Resource:
  496. POST /api/v1/users/password_change
  497. Payload:
  498. {
  499. "password_old": "some_password_old",
  500. "password_new": "some_password_new"
  501. }
  502. Response:
  503. {
  504. :message => 'ok'
  505. }
  506. Test:
  507. curl http://localhost/api/v1/users/password_change -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"password_old": "password_old", "password_new": "password_new"}'
  508. =end
  509. def password_change
  510. # check old password
  511. if !params[:password_old] || !PasswordPolicy::MaxLength.valid?(params[:password_old])
  512. render json: { message: 'failed', notice: [__('Current password needed!')] }, status: :unprocessable_entity
  513. return
  514. end
  515. current_password_verified = PasswordHash.verified?(current_user.password, params[:password_old])
  516. if !current_password_verified
  517. render json: { message: 'failed', notice: [__('Current password is wrong!')] }, status: :unprocessable_entity
  518. return
  519. end
  520. # set new password
  521. if !params[:password_new]
  522. render json: { message: 'failed', notice: [__('Please supply your new password!')] }, status: :unprocessable_entity
  523. return
  524. end
  525. result = PasswordPolicy.new(params[:password_new])
  526. if !result.valid?
  527. render json: { message: 'failed', notice: result.error }, status: :unprocessable_entity
  528. return
  529. end
  530. current_user.update!(password: params[:password_new])
  531. if current_user.email.present?
  532. NotificationFactory::Mailer.notification(
  533. template: 'password_change',
  534. user: current_user,
  535. objects: {
  536. user: current_user,
  537. }
  538. )
  539. end
  540. render json: { message: 'ok', user_login: current_user.login }, status: :ok
  541. end
  542. def password_check
  543. raise Exceptions::UnprocessableEntity, __("The required parameter 'password' is missing.") if params[:password].blank?
  544. begin
  545. Auth.new(current_user.login, params[:password], only_verify_password: true).valid!
  546. render json: { success: true }, status: :ok
  547. rescue Auth::Error::AuthenticationFailed
  548. render json: { success: false }, status: :ok
  549. end
  550. end
  551. =begin
  552. Resource:
  553. PUT /api/v1/users/preferences
  554. Payload:
  555. {
  556. "language": "de",
  557. "notification": true
  558. }
  559. Response:
  560. {
  561. :message => 'ok'
  562. }
  563. Test:
  564. curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  565. =end
  566. def preferences
  567. preferences_params = params.except(:controller, :action)
  568. if preferences_params.present?
  569. user = User.find(current_user.id)
  570. user.with_lock do
  571. preferences_params.permit!.to_h.each do |key, value|
  572. user.preferences[key.to_sym] = value
  573. end
  574. user.save!
  575. end
  576. end
  577. render json: { message: 'ok' }, status: :ok
  578. end
  579. =begin
  580. Resource:
  581. POST /api/v1/users/preferences_reset
  582. Response:
  583. {
  584. :message => 'ok'
  585. }
  586. Test:
  587. curl http://localhost/api/v1/users/preferences_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST'
  588. =end
  589. def preferences_notifications_reset
  590. User.reset_notifications_preferences!(current_user)
  591. render json: { message: 'ok' }, status: :ok
  592. end
  593. =begin
  594. Resource:
  595. PUT /api/v1/users/out_of_office
  596. Payload:
  597. {
  598. "out_of_office": true,
  599. "out_of_office_start_at": true,
  600. "out_of_office_end_at": true,
  601. "out_of_office_replacement_id": 123,
  602. "out_of_office_text": 'honeymoon'
  603. }
  604. Response:
  605. {
  606. :message => 'ok'
  607. }
  608. Test:
  609. 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}'
  610. =end
  611. def out_of_office
  612. user = User.find(current_user.id)
  613. user.with_lock do
  614. user.assign_attributes(
  615. out_of_office: params[:out_of_office],
  616. out_of_office_start_at: params[:out_of_office_start_at],
  617. out_of_office_end_at: params[:out_of_office_end_at],
  618. out_of_office_replacement_id: params[:out_of_office_replacement_id],
  619. )
  620. user.preferences[:out_of_office_text] = params[:out_of_office_text]
  621. user.save!
  622. end
  623. render json: { message: 'ok' }, status: :ok
  624. end
  625. =begin
  626. Resource:
  627. DELETE /api/v1/users/account
  628. Payload:
  629. {
  630. "provider": "twitter",
  631. "uid": 581482342942
  632. }
  633. Response:
  634. {
  635. :message => 'ok'
  636. }
  637. Test:
  638. curl http://localhost/api/v1/users/account -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  639. =end
  640. def account_remove
  641. # provider + uid to remove
  642. raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
  643. raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
  644. # remove from database
  645. record = Authorization.where(
  646. user_id: current_user.id,
  647. provider: params[:provider],
  648. uid: params[:uid],
  649. )
  650. raise Exceptions::UnprocessableEntity, __('No record found!') if !record.first
  651. record.destroy_all
  652. render json: { message: 'ok' }, status: :ok
  653. end
  654. =begin
  655. Resource:
  656. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  657. Response:
  658. <IMAGE>
  659. Test:
  660. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  661. =end
  662. def image
  663. # Cache images in the browser.
  664. expires_in(1.year.from_now, must_revalidate: true)
  665. file = Avatar.get_by_hash(params[:hash])
  666. if file
  667. file_content_type = file.preferences['Content-Type'] || file.preferences['Mime-Type']
  668. return serve_default_image if ActiveStorage.content_types_allowed_inline.exclude?(file_content_type)
  669. send_data(
  670. file.content,
  671. filename: file.filename,
  672. type: file_content_type,
  673. disposition: 'inline'
  674. )
  675. return
  676. end
  677. serve_default_image
  678. end
  679. =begin
  680. Resource:
  681. POST /api/v1/users/avatar
  682. Payload:
  683. {
  684. "avatar_full": "base64 url",
  685. }
  686. Response:
  687. {
  688. message: 'ok'
  689. }
  690. Test:
  691. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  692. =end
  693. def avatar_new
  694. service = Service::Avatar::ImageValidate.new
  695. file_full = service.execute(image_data: params[:avatar_full])
  696. if file_full[:error].present?
  697. render json: { error: file_full[:message] }, status: :unprocessable_entity
  698. return
  699. end
  700. file_resize = service.execute(image_data: params[:avatar_resize])
  701. if file_resize[:error].present?
  702. render json: { error: file_resize[:message] }, status: :unprocessable_entity
  703. return
  704. end
  705. render json: { avatar: Service::Avatar::Add.new(current_user: current_user).execute(full_image: file_full, resize_image: file_resize) }, status: :ok
  706. end
  707. def avatar_set_default
  708. # get & validate image
  709. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  710. # set as default
  711. avatar = Avatar.set_default('User', current_user.id, params[:id])
  712. # update user link
  713. user = User.find(current_user.id)
  714. user.update!(image: avatar.store_hash)
  715. render json: {}, status: :ok
  716. end
  717. def avatar_destroy
  718. # get & validate image
  719. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  720. # remove avatar
  721. Avatar.remove_one('User', current_user.id, params[:id])
  722. # update user link
  723. avatar = Avatar.get_default('User', current_user.id)
  724. user = User.find(current_user.id)
  725. user.update!(image: avatar.store_hash)
  726. render json: {}, status: :ok
  727. end
  728. def avatar_list
  729. # list of avatars
  730. result = Avatar.list('User', current_user.id)
  731. render json: { avatars: result }, status: :ok
  732. end
  733. # @path [GET] /users/import_example
  734. #
  735. # @summary Download of example CSV file.
  736. # @notes The requester have 'admin.user' permissions to be able to download it.
  737. # @example curl -u 'me@example.com:test' http://localhost:3000/api/v1/users/import_example
  738. #
  739. # @response_message 200 File download.
  740. # @response_message 403 Forbidden / Invalid session.
  741. def import_example
  742. send_data(
  743. User.csv_example,
  744. filename: 'user-example.csv',
  745. type: 'text/csv',
  746. disposition: 'attachment'
  747. )
  748. end
  749. # @path [POST] /users/import
  750. #
  751. # @summary Starts import.
  752. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  753. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  754. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  755. #
  756. # @response_message 201 Import started.
  757. # @response_message 403 Forbidden / Invalid session.
  758. def import_start
  759. string = params[:data]
  760. if string.blank? && params[:file].present?
  761. string = params[:file].read.force_encoding('utf-8')
  762. end
  763. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  764. result = User.csv_import(
  765. string: string,
  766. parse_params: {
  767. col_sep: params[:col_sep] || ',',
  768. },
  769. try: params[:try],
  770. delete: params[:delete],
  771. )
  772. render json: result, status: :ok
  773. end
  774. def two_factor_enabled_authentication_methods
  775. user = User.find(params[:id])
  776. render json: { methods: user.two_factor_enabled_authentication_methods }, status: :ok
  777. end
  778. private
  779. def password_login?
  780. return true if Setting.get('user_show_password_login')
  781. return true if Setting.where('name LIKE ? AND frontend = true', "#{SqlHelper.quote_like('auth_')}%")
  782. .map { |provider| provider.state_current['value'] }
  783. .all?(false)
  784. false
  785. end
  786. def clean_user_params
  787. User.param_cleanup(User.association_name_to_id_convert(params), true).merge(screen: 'create')
  788. end
  789. # @summary Creates a User record with the provided attribute values.
  790. # @notes For creating a user via agent interface
  791. #
  792. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  793. #
  794. # @response_message 200 [User] Created User record.
  795. # @response_message 403 Forbidden / Invalid session.
  796. def create_internal
  797. # permission check
  798. check_attributes_by_current_user_permission(params)
  799. user = User.new(clean_user_params)
  800. user.associations_from_param(params)
  801. user.save!
  802. if params[:invite].present?
  803. token = Token.create(action: 'PasswordReset', user_id: user.id)
  804. NotificationFactory::Mailer.notification(
  805. template: 'user_invite',
  806. user: user,
  807. objects: {
  808. token: token,
  809. user: user,
  810. current_user: current_user,
  811. }
  812. )
  813. end
  814. if response_expand?
  815. user = user.reload.attributes_with_association_names
  816. user.delete('password')
  817. render json: user, status: :created
  818. return
  819. end
  820. if response_full?
  821. result = {
  822. id: user.id,
  823. assets: user.assets({}),
  824. }
  825. render json: result, status: :created
  826. return
  827. end
  828. user = user.reload.attributes_with_association_ids
  829. user.delete('password')
  830. render json: user, status: :created
  831. end
  832. # @summary Creates a User record with the provided attribute values.
  833. # @notes For creating a user via public signup form
  834. #
  835. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  836. #
  837. # @response_message 200 [User] Created User record.
  838. # @response_message 403 Forbidden / Invalid session.
  839. def create_signup
  840. # check if feature is enabled
  841. if !Setting.get('user_create_account')
  842. raise Exceptions::UnprocessableEntity, __('Feature not enabled!')
  843. end
  844. # check signup option only after admin account is created
  845. if !params[:signup]
  846. raise Exceptions::UnprocessableEntity, __("The required parameter 'signup' is missing.")
  847. end
  848. # only allow fixed fields
  849. # TODO: https://github.com/zammad/zammad/issues/3295
  850. new_params = clean_user_params.slice(:firstname, :lastname, :email, :password)
  851. # check if user already exists
  852. if new_params[:email].blank?
  853. raise Exceptions::UnprocessableEntity, __('Attribute \'email\' required!')
  854. end
  855. email_taken_by = User.find_by email: new_params[:email].downcase.strip
  856. result = PasswordPolicy.new(new_params[:password])
  857. if !result.valid?
  858. render json: { error: result.error }, status: :unprocessable_entity
  859. return
  860. end
  861. user = User.new(new_params)
  862. user.role_ids = Role.signup_role_ids
  863. user.source = 'signup'
  864. if email_taken_by # show fake OK response to avoid leaking that email is already in use
  865. user.skip_ensure_uniq_email = true
  866. user.validate!
  867. result = User.password_reset_new_token(email_taken_by.email)
  868. NotificationFactory::Mailer.notification(
  869. template: 'signup_taken_reset',
  870. user: email_taken_by,
  871. objects: result,
  872. )
  873. render json: { message: 'ok' }, status: :created
  874. return
  875. end
  876. UserInfo.ensure_current_user_id do
  877. user.save!
  878. end
  879. result = User.signup_new_token(user)
  880. NotificationFactory::Mailer.notification(
  881. template: 'signup',
  882. user: user,
  883. objects: result,
  884. )
  885. render json: { message: 'ok' }, status: :created
  886. end
  887. # @summary Creates a User record with the provided attribute values.
  888. # @notes For creating an administrator account when setting up the system
  889. #
  890. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  891. #
  892. # @response_message 200 [User] Created User record.
  893. # @response_message 403 Forbidden / Invalid session.
  894. def create_admin
  895. if User.count > 2 # system and example users
  896. raise Exceptions::UnprocessableEntity, __('Administrator account already created')
  897. end
  898. # check if user already exists
  899. if clean_user_params[:email].blank?
  900. raise Exceptions::UnprocessableEntity, __('Attribute \'email\' required!')
  901. end
  902. # check password policy
  903. result = PasswordPolicy.new(clean_user_params[:password])
  904. if !result.valid?
  905. render json: { error: result.error }, status: :unprocessable_entity
  906. return
  907. end
  908. user = User.new(clean_user_params)
  909. user.associations_from_param(params)
  910. user.role_ids = Role.where(name: %w[Admin Agent]).pluck(:id)
  911. user.group_ids = Group.pluck(:id)
  912. UserInfo.ensure_current_user_id do
  913. user.save!
  914. end
  915. Setting.set('system_init_done', true)
  916. # fetch org logo
  917. if user.email.present?
  918. Service::Image.organization_suggest(user.email)
  919. end
  920. # load calendar
  921. Calendar.init_setup(request.remote_ip)
  922. # load text modules
  923. begin
  924. TextModule.load(request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us')
  925. rescue => e
  926. logger.error "Unable to load text modules #{request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us'}: #{e.message}"
  927. end
  928. render json: { message: 'ok' }, status: :created
  929. end
  930. def serve_default_image
  931. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  932. send_data(
  933. Base64.decode64(image),
  934. filename: 'image.gif',
  935. type: 'image/gif',
  936. disposition: 'inline'
  937. )
  938. end
  939. end