users_controller.rb 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class UsersController < ApplicationController
  3. include ChecksUserAttributesByCurrentUserPermission
  4. prepend_before_action :authentication_check, except: %i[create password_reset_send password_reset_verify image]
  5. prepend_before_action :authentication_check_only, only: [:create]
  6. # @path [GET] /users
  7. #
  8. # @summary Returns a list of User records.
  9. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  10. # get a list of all Users. If the requester is in the
  11. # role 'Customer' only just the own User record will be returned.
  12. #
  13. # @response_message 200 [Array<User>] List of matching User records.
  14. # @response_message 401 Invalid session.
  15. def index
  16. offset = 0
  17. per_page = 500
  18. if params[:page] && params[:per_page]
  19. offset = (params[:page].to_i - 1) * params[:per_page].to_i
  20. per_page = params[:per_page].to_i
  21. end
  22. if per_page > 500
  23. per_page = 500
  24. end
  25. # only allow customer to fetch him self
  26. users = if !current_user.permissions?(['admin.user', 'ticket.agent'])
  27. User.where(id: current_user.id).order(id: :asc).offset(offset).limit(per_page)
  28. else
  29. User.all.order(id: :asc).offset(offset).limit(per_page)
  30. end
  31. if response_expand?
  32. list = []
  33. users.each do |user|
  34. list.push user.attributes_with_association_names
  35. end
  36. render json: list, status: :ok
  37. return
  38. end
  39. if response_full?
  40. assets = {}
  41. item_ids = []
  42. users.each do |item|
  43. item_ids.push item.id
  44. assets = item.assets(assets)
  45. end
  46. render json: {
  47. record_ids: item_ids,
  48. assets: assets,
  49. }, status: :ok
  50. return
  51. end
  52. users_all = []
  53. users.each do |user|
  54. users_all.push User.lookup(id: user.id).attributes_with_association_ids
  55. end
  56. render json: users_all, status: :ok
  57. end
  58. # @path [GET] /users/{id}
  59. #
  60. # @summary Returns the User record with the requested identifier.
  61. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  62. # access all User records. If the requester is in the
  63. # role 'Customer' just the own User record is accessable.
  64. #
  65. # @parameter id(required) [Integer] The identifier matching the requested User.
  66. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  67. #
  68. # @response_message 200 [User] User record matching the requested identifier.
  69. # @response_message 401 Invalid session.
  70. def show
  71. user = User.find(params[:id])
  72. access!(user, 'read')
  73. if response_expand?
  74. result = user.attributes_with_association_names
  75. result.delete('password')
  76. render json: result
  77. return
  78. end
  79. if response_full?
  80. result = {
  81. id: user.id,
  82. assets: user.assets({}),
  83. }
  84. render json: result
  85. return
  86. end
  87. result = user.attributes_with_association_ids
  88. result.delete('password')
  89. render json: result
  90. end
  91. # @path [POST] /users
  92. #
  93. # @summary Creates a User record with the provided attribute values.
  94. # @notes TODO.
  95. #
  96. # @parameter User(required,body) [User] The attribute value structure needed to create a User record.
  97. #
  98. # @response_message 200 [User] Created User record.
  99. # @response_message 401 Invalid session.
  100. def create
  101. clean_params = User.association_name_to_id_convert(params)
  102. clean_params = User.param_cleanup(clean_params, true)
  103. # check if it's first user, the admin user
  104. # initial admin account
  105. count = User.all.count
  106. admin_account_exists = true
  107. if count <= 2
  108. admin_account_exists = false
  109. end
  110. # if it's a signup, add user to customer role
  111. if !current_user
  112. # check if feature is enabled
  113. if admin_account_exists && !Setting.get('user_create_account')
  114. raise Exceptions::UnprocessableEntity, 'Feature not enabled!'
  115. end
  116. # check signup option only after admin account is created
  117. if admin_account_exists && !params[:signup]
  118. raise Exceptions::UnprocessableEntity, 'Only signup with not authenticate user possible!'
  119. end
  120. # check if user already exists
  121. if clean_params[:email].blank?
  122. raise Exceptions::UnprocessableEntity, 'Attribute \'email\' required!'
  123. end
  124. # check if user already exists
  125. exists = User.find_by(email: clean_params[:email].downcase.strip)
  126. raise Exceptions::UnprocessableEntity, 'Email address is already used for other user.' if exists
  127. user = User.new(clean_params)
  128. user.associations_from_param(params)
  129. user.updated_by_id = 1
  130. user.created_by_id = 1
  131. # add first user as admin/agent and to all groups
  132. group_ids = []
  133. role_ids = []
  134. if count <= 2
  135. Role.where(name: %w[Admin Agent]).each do |role|
  136. role_ids.push role.id
  137. end
  138. Group.all.each do |group|
  139. group_ids.push group.id
  140. end
  141. # everybody else will go as customer per default
  142. else
  143. role_ids = Role.signup_role_ids
  144. end
  145. user.role_ids = role_ids
  146. user.group_ids = group_ids
  147. # remember source (in case show email verify banner)
  148. # if not initial user creation
  149. if admin_account_exists
  150. user.source = 'signup'
  151. end
  152. # else do assignment as defined
  153. else
  154. # permission check
  155. check_attributes_by_current_user_permission(params)
  156. user = User.new(clean_params)
  157. user.associations_from_param(params)
  158. end
  159. user.save!
  160. # if first user was added, set system init done
  161. if !admin_account_exists
  162. Setting.set('system_init_done', true)
  163. # fetch org logo
  164. if user.email.present?
  165. Service::Image.organization_suggest(user.email)
  166. end
  167. # load calendar
  168. Calendar.init_setup(request.remote_ip)
  169. # load text modules
  170. begin
  171. TextModule.load(request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us')
  172. rescue => e
  173. logger.error "Unable to load text modules #{request.env['HTTP_ACCEPT_LANGUAGE'] || 'en-us'}: #{e.message}"
  174. end
  175. end
  176. # send invitation if needed / only if session exists
  177. if params[:invite].present? && current_user
  178. sleep 5 if ENV['REMOTE_URL'].present?
  179. token = Token.create(action: 'PasswordReset', user_id: user.id)
  180. NotificationFactory::Mailer.notification(
  181. template: 'user_invite',
  182. user: user,
  183. objects: {
  184. token: token,
  185. user: user,
  186. current_user: current_user,
  187. }
  188. )
  189. end
  190. # send email verify
  191. if params[:signup].present? && !current_user
  192. result = User.signup_new_token(user)
  193. NotificationFactory::Mailer.notification(
  194. template: 'signup',
  195. user: user,
  196. objects: result,
  197. )
  198. end
  199. if response_expand?
  200. user = user.reload.attributes_with_association_names
  201. user.delete('password')
  202. render json: user, status: :created
  203. return
  204. end
  205. if response_full?
  206. result = {
  207. id: user.id,
  208. assets: user.assets({}),
  209. }
  210. render json: result, status: :created
  211. return
  212. end
  213. user = user.reload.attributes_with_association_ids
  214. user.delete('password')
  215. render json: user, status: :created
  216. end
  217. # @path [PUT] /users/{id}
  218. #
  219. # @summary Updates the User record matching the identifier with the provided attribute values.
  220. # @notes TODO.
  221. #
  222. # @parameter id(required) [Integer] The identifier matching the requested User record.
  223. # @parameter User(required,body) [User] The attribute value structure needed to update a User record.
  224. #
  225. # @response_message 200 [User] Updated User record.
  226. # @response_message 401 Invalid session.
  227. def update
  228. user = User.find(params[:id])
  229. access!(user, 'change')
  230. # permission check
  231. check_attributes_by_current_user_permission(params)
  232. user.with_lock do
  233. clean_params = User.association_name_to_id_convert(params)
  234. clean_params = User.param_cleanup(clean_params, true)
  235. user.update!(clean_params)
  236. # presence and permissions were checked via `check_attributes_by_current_user_permission`
  237. privileged_attributes = params.slice(:role_ids, :roles, :group_ids, :groups, :organization_ids, :organizations)
  238. if privileged_attributes.present?
  239. user.associations_from_param(privileged_attributes)
  240. end
  241. end
  242. if response_expand?
  243. user = user.reload.attributes_with_association_names
  244. user.delete('password')
  245. render json: user, status: :ok
  246. return
  247. end
  248. if response_full?
  249. result = {
  250. id: user.id,
  251. assets: user.assets({}),
  252. }
  253. render json: result, status: :ok
  254. return
  255. end
  256. user = user.reload.attributes_with_association_ids
  257. user.delete('password')
  258. render json: user, status: :ok
  259. end
  260. # @path [DELETE] /users/{id}
  261. #
  262. # @summary Deletes the User record matching the given identifier.
  263. # @notes The requester has to be in the role 'Admin' to be able to delete a User record.
  264. #
  265. # @parameter id(required) [User] The identifier matching the requested User record.
  266. #
  267. # @response_message 200 User successfully deleted.
  268. # @response_message 401 Invalid session.
  269. def destroy
  270. user = User.find(params[:id])
  271. access!(user, 'delete')
  272. model_references_check(User, params)
  273. model_destroy_render(User, params)
  274. end
  275. # @path [GET] /users/me
  276. #
  277. # @summary Returns the User record of current user.
  278. # @notes The requester needs to have a valid authentication.
  279. #
  280. # @parameter full [Bool] If set a Asset structure with all connected Assets gets returned.
  281. #
  282. # @response_message 200 [User] User record matching the requested identifier.
  283. # @response_message 401 Invalid session.
  284. def me
  285. if response_expand?
  286. user = current_user.attributes_with_association_names
  287. user.delete('password')
  288. render json: user, status: :ok
  289. return
  290. end
  291. if response_full?
  292. full = User.full(current_user.id)
  293. render json: full
  294. return
  295. end
  296. user = current_user.attributes_with_association_ids
  297. user.delete('password')
  298. render json: user
  299. end
  300. # @path [GET] /users/search
  301. #
  302. # @tag Search
  303. # @tag User
  304. #
  305. # @summary Searches the User matching the given expression(s).
  306. # @notes TODO: It's possible to use the SOLR search syntax.
  307. # The requester has to be in the role 'Admin' or 'Agent' to
  308. # be able to search for User records.
  309. #
  310. # @parameter query [String] The search query.
  311. # @parameter limit [Integer] The limit of search results.
  312. # @parameter role_ids(multi) [Array<String>] A list of Role identifiers to which the Users have to be allocated to.
  313. # @parameter full [Boolean] Defines if the result should be
  314. # true: { user_ids => [1,2,...], assets => {...} }
  315. # or false: [{:id => user.id, :label => "firstname lastname <email>", :value => "firstname lastname <email>"},...].
  316. #
  317. # @response_message 200 [Array<User>] A list of User records matching the search term.
  318. # @response_message 401 Invalid session.
  319. def search
  320. raise Exceptions::NotAuthorized if !current_user.permissions?(['ticket.agent', 'admin.user'])
  321. per_page = params[:per_page] || params[:limit] || 100
  322. per_page = per_page.to_i
  323. if per_page > 500
  324. per_page = 500
  325. end
  326. page = params[:page] || 1
  327. page = page.to_i
  328. offset = (page - 1) * per_page
  329. query = params[:query]
  330. if query.respond_to?(:permit!)
  331. query.permit!.to_h
  332. end
  333. query = params[:query] || params[:term]
  334. if query.respond_to?(:permit!)
  335. query = query.permit!.to_h
  336. end
  337. query_params = {
  338. query: query,
  339. limit: per_page,
  340. offset: offset,
  341. sort_by: params[:sort_by],
  342. order_by: params[:order_by],
  343. current_user: current_user,
  344. }
  345. %i[role_ids permissions].each do |key|
  346. next if params[key].blank?
  347. query_params[key] = params[key]
  348. end
  349. # do query
  350. user_all = User.search(query_params)
  351. if response_expand?
  352. list = []
  353. user_all.each do |user|
  354. list.push user.attributes_with_association_names
  355. end
  356. render json: list, status: :ok
  357. return
  358. end
  359. # build result list
  360. if params[:label] || params[:term]
  361. users = []
  362. user_all.each do |user|
  363. realname = user.fullname
  364. if user.email.present? && realname != user.email
  365. realname = "#{realname} <#{user.email}>"
  366. end
  367. a = if params[:term]
  368. { id: user.id, label: realname, value: user.email }
  369. else
  370. { id: user.id, label: realname, value: realname }
  371. end
  372. users.push a
  373. end
  374. # return result
  375. render json: users
  376. return
  377. end
  378. if response_full?
  379. user_ids = []
  380. assets = {}
  381. user_all.each do |user|
  382. assets = user.assets(assets)
  383. user_ids.push user.id
  384. end
  385. # return result
  386. render json: {
  387. assets: assets,
  388. user_ids: user_ids.uniq,
  389. }
  390. return
  391. end
  392. list = []
  393. user_all.each do |user|
  394. list.push user.attributes_with_association_ids
  395. end
  396. render json: list, status: :ok
  397. end
  398. # @path [GET] /users/history/{id}
  399. #
  400. # @tag History
  401. # @tag User
  402. #
  403. # @summary Returns the History records of a User record matching the given identifier.
  404. # @notes The requester has to be in the role 'Admin' or 'Agent' to
  405. # get the History records of a User record.
  406. #
  407. # @parameter id(required) [Integer] The identifier matching the requested User record.
  408. #
  409. # @response_message 200 [History] The History records of the requested User record.
  410. # @response_message 401 Invalid session.
  411. def history
  412. raise Exceptions::NotAuthorized if !current_user.permissions?(['admin.user', 'ticket.agent'])
  413. # get user data
  414. user = User.find(params[:id])
  415. # get history of user
  416. render json: user.history_get(true)
  417. end
  418. =begin
  419. Resource:
  420. POST /api/v1/users/email_verify
  421. Payload:
  422. {
  423. "token": "SoMeToKeN",
  424. }
  425. Response:
  426. {
  427. :message => 'ok'
  428. }
  429. Test:
  430. curl http://localhost/api/v1/users/email_verify -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"token": "SoMeToKeN"}'
  431. =end
  432. def email_verify
  433. raise Exceptions::UnprocessableEntity, 'No token!' if !params[:token]
  434. user = User.signup_verify_via_token(params[:token], current_user)
  435. raise Exceptions::UnprocessableEntity, 'Invalid token!' if !user
  436. render json: { message: 'ok', user_email: user.email }, status: :ok
  437. end
  438. =begin
  439. Resource:
  440. POST /api/v1/users/email_verify_send
  441. Payload:
  442. {
  443. "email": "some_email@example.com"
  444. }
  445. Response:
  446. {
  447. :message => 'ok'
  448. }
  449. Test:
  450. 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"}'
  451. =end
  452. def email_verify_send
  453. raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]
  454. user = User.find_by(email: params[:email].downcase)
  455. if !user
  456. # result is always positive to avoid leaking of existing user accounts
  457. render json: { message: 'ok' }, status: :ok
  458. return
  459. end
  460. #if user.verified == true
  461. # render json: { error: 'Already verified!' }, status: :unprocessable_entity
  462. # return
  463. #end
  464. Token.create(action: 'Signup', user_id: user.id)
  465. result = User.signup_new_token(user)
  466. if result && result[:token]
  467. user = result[:user]
  468. NotificationFactory::Mailer.notification(
  469. template: 'signup',
  470. user: user,
  471. objects: result
  472. )
  473. # only if system is in develop mode, send token back to browser for browser tests
  474. if Setting.get('developer_mode') == true
  475. render json: { message: 'ok', token: result[:token].name }, status: :ok
  476. return
  477. end
  478. # token sent to user, send ok to browser
  479. render json: { message: 'ok' }, status: :ok
  480. return
  481. end
  482. # unable to generate token
  483. render json: { message: 'failed' }, status: :ok
  484. end
  485. =begin
  486. Resource:
  487. POST /api/v1/users/password_reset
  488. Payload:
  489. {
  490. "username": "some user name"
  491. }
  492. Response:
  493. {
  494. :message => 'ok'
  495. }
  496. Test:
  497. curl http://localhost/api/v1/users/password_reset -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"username": "some_username"}'
  498. =end
  499. def password_reset_send
  500. # check if feature is enabled
  501. raise Exceptions::UnprocessableEntity, 'Feature not enabled!' if !Setting.get('user_lost_password')
  502. result = User.password_reset_new_token(params[:username])
  503. if result && result[:token]
  504. # send mail
  505. user = result[:user]
  506. NotificationFactory::Mailer.notification(
  507. template: 'password_reset',
  508. user: user,
  509. objects: result
  510. )
  511. # only if system is in develop mode, send token back to browser for browser tests
  512. if Setting.get('developer_mode') == true
  513. render json: { message: 'ok', token: result[:token].name }, status: :ok
  514. return
  515. end
  516. end
  517. # result is always positive to avoid leaking of existing user accounts
  518. render json: { message: 'ok' }, status: :ok
  519. end
  520. =begin
  521. Resource:
  522. POST /api/v1/users/password_reset_verify
  523. Payload:
  524. {
  525. "token": "SoMeToKeN",
  526. "password": "new_password"
  527. }
  528. Response:
  529. {
  530. :message => 'ok'
  531. }
  532. Test:
  533. 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"}'
  534. =end
  535. def password_reset_verify
  536. if params[:password]
  537. # check password policy
  538. result = password_policy(params[:password])
  539. if result != true
  540. render json: { message: 'failed', notice: result }, status: :ok
  541. return
  542. end
  543. # set new password with token
  544. user = User.password_reset_via_token(params[:token], params[:password])
  545. # send mail
  546. if user
  547. NotificationFactory::Mailer.notification(
  548. template: 'password_change',
  549. user: user,
  550. objects: {
  551. user: user,
  552. current_user: current_user,
  553. }
  554. )
  555. end
  556. else
  557. user = User.by_reset_token(params[:token])
  558. end
  559. if user
  560. render json: { message: 'ok', user_login: user.login }, status: :ok
  561. else
  562. render json: { message: 'failed' }, status: :ok
  563. end
  564. end
  565. =begin
  566. Resource:
  567. POST /api/v1/users/password_change
  568. Payload:
  569. {
  570. "password_old": "some_password_old",
  571. "password_new": "some_password_new"
  572. }
  573. Response:
  574. {
  575. :message => 'ok'
  576. }
  577. Test:
  578. 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"}'
  579. =end
  580. def password_change
  581. # check old password
  582. if !params[:password_old]
  583. render json: { message: 'failed', notice: ['Current password needed!'] }, status: :ok
  584. return
  585. end
  586. user = User.authenticate(current_user.login, params[:password_old])
  587. if !user
  588. render json: { message: 'failed', notice: ['Current password is wrong!'] }, status: :ok
  589. return
  590. end
  591. # set new password
  592. if !params[:password_new]
  593. render json: { message: 'failed', notice: ['Please supply your new password!'] }, status: :ok
  594. return
  595. end
  596. # check password policy
  597. result = password_policy(params[:password_new])
  598. if result != true
  599. render json: { message: 'failed', notice: result }, status: :ok
  600. return
  601. end
  602. user.update!(password: params[:password_new])
  603. NotificationFactory::Mailer.notification(
  604. template: 'password_change',
  605. user: user,
  606. objects: {
  607. user: user,
  608. current_user: current_user,
  609. }
  610. )
  611. render json: { message: 'ok', user_login: user.login }, status: :ok
  612. end
  613. =begin
  614. Resource:
  615. PUT /api/v1/users/preferences
  616. Payload:
  617. {
  618. "language": "de",
  619. "notification": true
  620. }
  621. Response:
  622. {
  623. :message => 'ok'
  624. }
  625. Test:
  626. curl http://localhost/api/v1/users/preferences -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"language": "de", "notifications": true}'
  627. =end
  628. def preferences
  629. raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
  630. preferences_params = params.except(:controller, :action)
  631. if preferences_params.present?
  632. user = User.find(current_user.id)
  633. user.with_lock do
  634. preferences_params.permit!.to_h.each do |key, value|
  635. user.preferences[key.to_sym] = value
  636. end
  637. user.save!
  638. end
  639. end
  640. render json: { message: 'ok' }, status: :ok
  641. end
  642. =begin
  643. Resource:
  644. PUT /api/v1/users/out_of_office
  645. Payload:
  646. {
  647. "out_of_office": true,
  648. "out_of_office_start_at": true,
  649. "out_of_office_end_at": true,
  650. "out_of_office_replacement_id": 123,
  651. "out_of_office_text": 'honeymoon'
  652. }
  653. Response:
  654. {
  655. :message => 'ok'
  656. }
  657. Test:
  658. 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}'
  659. =end
  660. def out_of_office
  661. raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
  662. user = User.find(current_user.id)
  663. user.with_lock do
  664. user.assign_attributes(
  665. out_of_office: params[:out_of_office],
  666. out_of_office_start_at: params[:out_of_office_start_at],
  667. out_of_office_end_at: params[:out_of_office_end_at],
  668. out_of_office_replacement_id: params[:out_of_office_replacement_id],
  669. )
  670. user.preferences[:out_of_office_text] = params[:out_of_office_text]
  671. user.save!
  672. end
  673. render json: { message: 'ok' }, status: :ok
  674. end
  675. =begin
  676. Resource:
  677. DELETE /api/v1/users/account
  678. Payload:
  679. {
  680. "provider": "twitter",
  681. "uid": 581482342942
  682. }
  683. Response:
  684. {
  685. :message => 'ok'
  686. }
  687. Test:
  688. curl http://localhost/api/v1/users/account -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"provider": "twitter", "uid": 581482342942}'
  689. =end
  690. def account_remove
  691. raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
  692. # provider + uid to remove
  693. raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
  694. raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
  695. # remove from database
  696. record = Authorization.where(
  697. user_id: current_user.id,
  698. provider: params[:provider],
  699. uid: params[:uid],
  700. )
  701. raise Exceptions::UnprocessableEntity, 'No record found!' if !record.first
  702. record.destroy_all
  703. render json: { message: 'ok' }, status: :ok
  704. end
  705. =begin
  706. Resource:
  707. GET /api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7
  708. Response:
  709. <IMAGE>
  710. Test:
  711. curl http://localhost/api/v1/users/image/8d6cca1c6bdc226cf2ba131e264ca2c7 -v -u #{login}:#{password}
  712. =end
  713. def image
  714. # cache image
  715. response.headers['Expires'] = 1.year.from_now.httpdate
  716. response.headers['Cache-Control'] = 'cache, store, max-age=31536000, must-revalidate'
  717. response.headers['Pragma'] = 'cache'
  718. file = Avatar.get_by_hash(params[:hash])
  719. if file
  720. send_data(
  721. file.content,
  722. filename: file.filename,
  723. type: file.preferences['Content-Type'] || file.preferences['Mime-Type'],
  724. disposition: 'inline'
  725. )
  726. return
  727. end
  728. # serve default image
  729. image = 'R0lGODdhMAAwAOMAAMzMzJaWlr6+vqqqqqOjo8XFxbe3t7GxsZycnAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAMAAwAAAEcxDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru98TwuAA+KQAQqJK8EAgBAgMEqmkzUgBIeSwWGZtR5XhSqAULACCoGCJGwlm1MGQrq9RqgB8fm4ZTUgDBIEcRR9fz6HiImKi4yNjo+QkZKTlJWWkBEAOw=='
  730. send_data(
  731. Base64.decode64(image),
  732. filename: 'image.gif',
  733. type: 'image/gif',
  734. disposition: 'inline'
  735. )
  736. end
  737. =begin
  738. Resource:
  739. POST /api/v1/users/avatar
  740. Payload:
  741. {
  742. "avatar_full": "base64 url",
  743. }
  744. Response:
  745. {
  746. message: 'ok'
  747. }
  748. Test:
  749. curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"avatar": "base64 url"}'
  750. =end
  751. def avatar_new
  752. return if !valid_session_with_user
  753. # get & validate image
  754. file_full = StaticAssets.data_url_attributes(params[:avatar_full])
  755. file_resize = StaticAssets.data_url_attributes(params[:avatar_resize])
  756. avatar = Avatar.add(
  757. object: 'User',
  758. o_id: current_user.id,
  759. full: {
  760. content: file_full[:content],
  761. mime_type: file_full[:mime_type],
  762. },
  763. resize: {
  764. content: file_resize[:content],
  765. mime_type: file_resize[:mime_type],
  766. },
  767. source: 'upload ' + Time.zone.now.to_s,
  768. deletable: true,
  769. )
  770. # update user link
  771. user = User.find(current_user.id)
  772. user.update!(image: avatar.store_hash)
  773. render json: { avatar: avatar }, status: :ok
  774. end
  775. def avatar_set_default
  776. return if !valid_session_with_user
  777. # get & validate image
  778. raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id]
  779. # set as default
  780. avatar = Avatar.set_default('User', current_user.id, params[:id])
  781. # update user link
  782. user = User.find(current_user.id)
  783. user.update!(image: avatar.store_hash)
  784. render json: {}, status: :ok
  785. end
  786. def avatar_destroy
  787. return if !valid_session_with_user
  788. # get & validate image
  789. raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id]
  790. # remove avatar
  791. Avatar.remove_one('User', current_user.id, params[:id])
  792. # update user link
  793. avatar = Avatar.get_default('User', current_user.id)
  794. user = User.find(current_user.id)
  795. user.update!(image: avatar.store_hash)
  796. render json: {}, status: :ok
  797. end
  798. def avatar_list
  799. return if !valid_session_with_user
  800. # list of avatars
  801. result = Avatar.list('User', current_user.id)
  802. render json: { avatars: result }, status: :ok
  803. end
  804. # @path [GET] /users/import_example
  805. #
  806. # @summary Download of example CSV file.
  807. # @notes The requester have 'admin.user' permissions to be able to download it.
  808. # @example curl -u 'me@example.com:test' http://localhost:3000/api/v1/users/import_example
  809. #
  810. # @response_message 200 File download.
  811. # @response_message 401 Invalid session.
  812. def import_example
  813. permission_check('admin.user')
  814. send_data(
  815. User.csv_example,
  816. filename: 'user-example.csv',
  817. type: 'text/csv',
  818. disposition: 'attachment'
  819. )
  820. end
  821. # @path [POST] /users/import
  822. #
  823. # @summary Starts import.
  824. # @notes The requester have 'admin.text_module' permissions to be create a new import.
  825. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import?try=true'
  826. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/users.csv' 'https://your.zammad/api/v1/users/import'
  827. #
  828. # @response_message 201 Import started.
  829. # @response_message 401 Invalid session.
  830. def import_start
  831. permission_check('admin.user')
  832. string = params[:data]
  833. if string.blank? && params[:file].present?
  834. string = params[:file].read.force_encoding('utf-8')
  835. end
  836. raise Exceptions::UnprocessableEntity, 'No source data submitted!' if string.blank?
  837. result = User.csv_import(
  838. string: string,
  839. parse_params: {
  840. col_sep: params[:col_sep] || ',',
  841. },
  842. try: params[:try],
  843. delete: params[:delete],
  844. )
  845. render json: result, status: :ok
  846. end
  847. private
  848. def password_policy(password)
  849. if Setting.get('password_min_size').to_i > password.length
  850. return ["Can\'t update password, it must be at least %s characters long!", Setting.get('password_min_size')]
  851. end
  852. if Setting.get('password_need_digit').to_i == 1 && password !~ /\d/
  853. return ["Can't update password, it must contain at least 1 digit!"]
  854. end
  855. if Setting.get('password_min_2_lower_2_upper_characters').to_i == 1 && ( password !~ /[A-Z].*[A-Z]/ || password !~ /[a-z].*[a-z]/ )
  856. return ["Can't update password, it must contain at least 2 lowercase and 2 uppercase characters!"]
  857. end
  858. true
  859. end
  860. end