users_controller.rb 27 KB

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