users_controller.rb 28 KB

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