users_controller.rb 28 KB

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