users_controller.rb 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. # Copyright (C) 2012-2022 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]
  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).order(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] = 'update'
  111. user.update!(clean_params)
  112. # presence and permissions were checked via `check_attributes_by_current_user_permission`
  113. privileged_attributes = params.slice(:role_ids, :roles, :group_ids, :groups, :organization_ids, :organizations)
  114. if privileged_attributes.present?
  115. user.associations_from_param(privileged_attributes)
  116. end
  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 = "#{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/password_reset
  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/password_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  375. =end
  376. def password_reset_send
  377. # check if feature is enabled
  378. raise Exceptions::UnprocessableEntity, __('Feature not enabled!') if !Setting.get('user_lost_password')
  379. result = User.password_reset_new_token(params[:username])
  380. if result && result[:token]
  381. # unable to send email
  382. if !result[:user] || result[:user].email.blank?
  383. render json: { message: 'failed' }, status: :ok
  384. return
  385. end
  386. # send password reset emails
  387. NotificationFactory::Mailer.notification(
  388. template: 'password_reset',
  389. user: result[:user],
  390. objects: result
  391. )
  392. end
  393. # result is always positive to avoid leaking of existing user accounts
  394. render json: { message: 'ok' }, status: :ok
  395. end
  396. =begin
  397. Resource:
  398. POST /api/v1/users/password_reset_verify
  399. Payload:
  400. {
  401. "token": "SoMeToKeN",
  402. "password": "new_password"
  403. }
  404. Response:
  405. {
  406. :message => 'ok'
  407. }
  408. Test:
  409. 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"}'
  410. =end
  411. def password_reset_verify
  412. # check if feature is enabled
  413. raise Exceptions::UnprocessableEntity, __('Feature not enabled!') if !Setting.get('user_lost_password')
  414. raise Exceptions::UnprocessableEntity, 'token param needed!' if params[:token].blank?
  415. # if no password is given, verify token only
  416. if params[:password].blank?
  417. user = User.by_reset_token(params[:token])
  418. if user
  419. render json: { message: 'ok', user_login: user.login }, status: :ok
  420. return
  421. end
  422. render json: { message: 'failed' }, status: :ok
  423. return
  424. end
  425. result = PasswordPolicy.new(params[:password])
  426. if !result.valid?
  427. render json: { message: 'failed', notice: result.error }, status: :ok
  428. return
  429. end
  430. # set new password with token
  431. user = User.password_reset_via_token(params[:token], params[:password])
  432. # send mail
  433. if !user || user.email.blank?
  434. render json: { message: 'failed' }, status: :ok
  435. return
  436. end
  437. NotificationFactory::Mailer.notification(
  438. template: 'password_change',
  439. user: user,
  440. objects: {
  441. user: user,
  442. current_user: current_user,
  443. }
  444. )
  445. render json: { message: 'ok', user_login: user.login }, status: :ok
  446. end
  447. =begin
  448. Resource:
  449. POST /api/v1/users/password_change
  450. Payload:
  451. {
  452. "password_old": "some_password_old",
  453. "password_new": "some_password_new"
  454. }
  455. Response:
  456. {
  457. :message => 'ok'
  458. }
  459. Test:
  460. 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"}'
  461. =end
  462. def password_change
  463. # check old password
  464. if !params[:password_old] || !PasswordPolicy::MaxLength.valid?(params[:password_old])
  465. render json: { message: 'failed', notice: [__('Current password needed!')] }, status: :unprocessable_entity
  466. return
  467. end
  468. current_password_verified = PasswordHash.verified?(current_user.password, params[:password_old])
  469. if !current_password_verified
  470. render json: { message: 'failed', notice: [__('Current password is wrong!')] }, status: :unprocessable_entity
  471. return
  472. end
  473. # set new password
  474. if !params[:password_new]
  475. render json: { message: 'failed', notice: [__('Please supply your new password!')] }, status: :unprocessable_entity
  476. return
  477. end
  478. result = PasswordPolicy.new(params[:password_new])
  479. if !result.valid?
  480. render json: { message: 'failed', notice: result.error }, status: :unprocessable_entity
  481. return
  482. end
  483. current_user.update!(password: params[:password_new])
  484. if current_user.email.present?
  485. NotificationFactory::Mailer.notification(
  486. template: 'password_change',
  487. user: current_user,
  488. objects: {
  489. user: current_user,
  490. }
  491. )
  492. end
  493. render json: { message: 'ok', user_login: current_user.login }, status: :ok
  494. end
  495. =begin
  496. Resource:
  497. PUT /api/v1/users/preferences
  498. Payload:
  499. {
  500. "language": "de",
  501. "notification": true
  502. }
  503. Response:
  504. {
  505. :message => 'ok'
  506. }
  507. Test:
  508. curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  509. =end
  510. def preferences
  511. preferences_params = params.except(:controller, :action)
  512. if preferences_params.present?
  513. user = User.find(current_user.id)
  514. user.with_lock do
  515. preferences_params.permit!.to_h.each do |key, value|
  516. user.preferences[key.to_sym] = value
  517. end
  518. user.save!
  519. end
  520. end
  521. render json: { message: 'ok' }, status: :ok
  522. end
  523. =begin
  524. Resource:
  525. PUT /api/v1/users/out_of_office
  526. Payload:
  527. {
  528. "out_of_office": true,
  529. "out_of_office_start_at": true,
  530. "out_of_office_end_at": true,
  531. "out_of_office_replacement_id": 123,
  532. "out_of_office_text": 'honeymoon'
  533. }
  534. Response:
  535. {
  536. :message => 'ok'
  537. }
  538. Test:
  539. 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}'
  540. =end
  541. def out_of_office
  542. user = User.find(current_user.id)
  543. user.with_lock do
  544. user.assign_attributes(
  545. out_of_office: params[:out_of_office],
  546. out_of_office_start_at: params[:out_of_office_start_at],
  547. out_of_office_end_at: params[:out_of_office_end_at],
  548. out_of_office_replacement_id: params[:out_of_office_replacement_id],
  549. )
  550. user.preferences[:out_of_office_text] = params[:out_of_office_text]
  551. user.save!
  552. end
  553. render json: { message: 'ok' }, status: :ok
  554. end
  555. =begin
  556. Resource:
  557. DELETE /api/v1/users/account
  558. Payload:
  559. {
  560. "provider": "twitter",
  561. "uid": 581482342942
  562. }
  563. Response:
  564. {
  565. :message => 'ok'
  566. }
  567. Test:
  568. curl http://localhost/api/v1/users/account -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  569. =end
  570. def account_remove
  571. # provider + uid to remove
  572. raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
  573. raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
  574. # remove from database
  575. record = Authorization.where(
  576. user_id: current_user.id,
  577. provider: params[:provider],
  578. uid: params[:uid],
  579. )
  580. raise Exceptions::UnprocessableEntity, __('No record found!') if !record.first
  581. record.destroy_all
  582. render json: { message: 'ok' }, status: :ok
  583. end
  584. =begin
  585. Resource:
  586. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  587. Response:
  588. <IMAGE>
  589. Test:
  590. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  591. =end
  592. def image
  593. # cache image
  594. response.headers['Expires'] = 1.year.from_now.httpdate
  595. response.headers['Cache-Control'] = 'cache, store, max-age=31536000, must-revalidate'
  596. response.headers['Pragma'] = 'cache'
  597. file = Avatar.get_by_hash(params[:hash])
  598. if file
  599. file_content_type = file.preferences['Content-Type'] || file.preferences['Mime-Type']
  600. return serve_default_image if ActiveStorage.content_types_allowed_inline.exclude?(file_content_type)
  601. send_data(
  602. file.content,
  603. filename: file.filename,
  604. type: file_content_type,
  605. disposition: 'inline'
  606. )
  607. return
  608. end
  609. serve_default_image
  610. end
  611. =begin
  612. Resource:
  613. POST /api/v1/users/avatar
  614. Payload:
  615. {
  616. "avatar_full": "base64 url",
  617. }
  618. Response:
  619. {
  620. message: 'ok'
  621. }
  622. Test:
  623. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  624. =end
  625. def avatar_new
  626. # get & validate image
  627. begin
  628. file_full = StaticAssets.data_url_attributes(params[:avatar_full])
  629. rescue
  630. render json: { error: __('The full-size image is invalid.') }, status: :unprocessable_entity
  631. return
  632. end
  633. web_image_content_types = Rails.application.config.active_storage.web_image_content_types
  634. if web_image_content_types.exclude?(file_full[:mime_type])
  635. render json: { error: __('The MIME type of the full-size image is invalid.') }, status: :unprocessable_entity
  636. return
  637. end
  638. begin
  639. file_resize = StaticAssets.data_url_attributes(params[:avatar_resize])
  640. rescue
  641. render json: { error: __('The resized image is invalid.') }, status: :unprocessable_entity
  642. return
  643. end
  644. if web_image_content_types.exclude?(file_resize[:mime_type])
  645. render json: { error: __('The MIME type of the resized image is invalid.') }, status: :unprocessable_entity
  646. return
  647. end
  648. avatar = Avatar.add(
  649. object: 'User',
  650. o_id: current_user.id,
  651. full: {
  652. content: file_full[:content],
  653. mime_type: file_full[:mime_type],
  654. },
  655. resize: {
  656. content: file_resize[:content],
  657. mime_type: file_resize[:mime_type],
  658. },
  659. source: "upload #{Time.zone.now}",
  660. deletable: true,
  661. )
  662. # update user link
  663. user = User.find(current_user.id)
  664. user.update!(image: avatar.store_hash)
  665. render json: { avatar: avatar }, status: :ok
  666. end
  667. def avatar_set_default
  668. # get & validate image
  669. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  670. # set as default
  671. avatar = Avatar.set_default('User', current_user.id, params[:id])
  672. # update user link
  673. user = User.find(current_user.id)
  674. user.update!(image: avatar.store_hash)
  675. render json: {}, status: :ok
  676. end
  677. def avatar_destroy
  678. # get & validate image
  679. raise Exceptions::UnprocessableEntity, __("The required parameter 'id' is missing.") if !params[:id]
  680. # remove avatar
  681. Avatar.remove_one('User', current_user.id, params[:id])
  682. # update user link
  683. avatar = Avatar.get_default('User', current_user.id)
  684. user = User.find(current_user.id)
  685. user.update!(image: avatar.store_hash)
  686. render json: {}, status: :ok
  687. end
  688. def avatar_list
  689. # list of avatars
  690. result = Avatar.list('User', current_user.id)
  691. render json: { avatars: result }, status: :ok
  692. end
  693. # @path [GET] /users/import_example
  694. #
  695. # @summary Download of example CSV file.
  696. # @notes The requester have 'admin.user' permissions to be able to download it.
  697. # @example curl -u 'me@example.com:test' http://localhost:3000/api/v1/users/import_example
  698. #
  699. # @response_message 200 File download.
  700. # @response_message 403 Forbidden / Invalid session.
  701. def import_example
  702. send_data(
  703. User.csv_example,
  704. filename: 'user-example.csv',
  705. type: 'text/csv',
  706. disposition: 'attachment'
  707. )
  708. end
  709. # @path [POST] /users/import
  710. #
  711. # @summary Starts import.
  712. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  713. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  714. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  715. #
  716. # @response_message 201 Import started.
  717. # @response_message 403 Forbidden / Invalid session.
  718. def import_start
  719. string = params[:data]
  720. if string.blank? && params[:file].present?
  721. string = params[:file].read.force_encoding('utf-8')
  722. end
  723. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  724. result = User.csv_import(
  725. string: string,
  726. parse_params: {
  727. col_sep: params[:col_sep] || ',',
  728. },
  729. try: params[:try],
  730. delete: params[:delete],
  731. )
  732. render json: result, status: :ok
  733. end
  734. private
  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 if feature is enabled
  790. if !Setting.get('user_create_account')
  791. raise Exceptions::UnprocessableEntity, __('Feature not enabled!')
  792. end
  793. # check signup option only after admin account is created
  794. if !params[:signup]
  795. raise Exceptions::UnprocessableEntity, __("The required parameter 'signup' is missing.")
  796. end
  797. # check if user already exists
  798. if clean_user_params[:email].blank?
  799. raise Exceptions::UnprocessableEntity, __('Attribute \'email\' required!')
  800. end
  801. email_taken_by = User.find_by email: clean_user_params[:email].downcase.strip
  802. result = PasswordPolicy.new(clean_user_params[:password])
  803. if !result.valid?
  804. render json: { error: result.error }, status: :unprocessable_entity
  805. return
  806. end
  807. user = User.new(clean_user_params)
  808. user.associations_from_param(params)
  809. user.role_ids = Role.signup_role_ids
  810. user.source = 'signup'
  811. if email_taken_by # show fake OK response to avoid leaking that email is already in use
  812. user.skip_ensure_uniq_email = true
  813. user.validate!
  814. result = User.password_reset_new_token(email_taken_by.email)
  815. NotificationFactory::Mailer.notification(
  816. template: 'signup_taken_reset',
  817. user: email_taken_by,
  818. objects: result,
  819. )
  820. render json: { message: 'ok' }, status: :created
  821. return
  822. end
  823. UserInfo.ensure_current_user_id do
  824. user.save!
  825. end
  826. result = User.signup_new_token(user)
  827. NotificationFactory::Mailer.notification(
  828. template: 'signup',
  829. user: user,
  830. objects: result,
  831. )
  832. render json: { message: 'ok' }, status: :created
  833. end
  834. # @summary Creates a User record with the provided attribute values.
  835. # @notes For creating an administrator account when setting up the system
  836. #
  837. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  838. #
  839. # @response_message 200 [User] Created User record.
  840. # @response_message 403 Forbidden / Invalid session.
  841. def create_admin
  842. if User.count > 2 # system and example users
  843. raise Exceptions::UnprocessableEntity, __('Administrator account already created')
  844. end
  845. # check if user already exists
  846. if clean_user_params[:email].blank?
  847. raise Exceptions::UnprocessableEntity, __('Attribute \'email\' required!')
  848. end
  849. # check password policy
  850. result = PasswordPolicy.new(clean_user_params[:password])
  851. if !result.valid?
  852. render json: { error: result.error }, status: :unprocessable_entity
  853. return
  854. end
  855. user = User.new(clean_user_params)
  856. user.associations_from_param(params)
  857. user.role_ids = Role.where(name: %w[Admin Agent]).pluck(:id)
  858. user.group_ids = Group.all.pluck(:id)
  859. UserInfo.ensure_current_user_id do
  860. user.save!
  861. end
  862. Setting.set('system_init_done', true)
  863. # fetch org logo
  864. if user.email.present?
  865. Service::Image.organization_suggest(user.email)
  866. end
  867. # load calendar
  868. Calendar.init_setup(request.remote_ip)
  869. # load text modules
  870. begin
  871. TextModule.load(request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us')
  872. rescue => e
  873. logger.error "Unable to load text modules #{request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us'}: #{e.message}"
  874. end
  875. render json: { message: 'ok' }, status: :created
  876. end
  877. def serve_default_image
  878. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  879. send_data(
  880. Base64.decode64(image),
  881. filename: 'image.gif',
  882. type: 'image/gif',
  883. disposition: 'inline'
  884. )
  885. end
  886. end