user_access_token_controller.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class UserAccessTokenController < ApplicationController
  3. prepend_before_action { authentication_check(permission: 'user_preferences.access_token') }
  4. def index
  5. tokens = Token.where(action: 'api', persistent: true, user_id: current_user.id).order('updated_at DESC, label ASC')
  6. token_list = []
  7. tokens.each do |token|
  8. attributes = token.attributes
  9. attributes.delete('persistent')
  10. attributes.delete('name')
  11. token_list.push attributes
  12. end
  13. local_permissions = current_user.permissions
  14. local_permissions_new = {}
  15. local_permissions.each_key do |key|
  16. keys = Object.const_get('Permission').with_parents(key)
  17. keys.each do |local_key|
  18. next if local_permissions_new.key?([local_key])
  19. if local_permissions[local_key] == true
  20. local_permissions_new[local_key] = true
  21. next
  22. end
  23. local_permissions_new[local_key] = false
  24. end
  25. end
  26. permissions = []
  27. Permission.all.where(active: true).order(:name).each do |permission|
  28. next if !local_permissions_new.key?(permission.name) && !current_user.permissions?(permission.name)
  29. permission_attributes = permission.attributes
  30. if local_permissions_new[permission.name] == false
  31. permission_attributes['preferences']['disabled'] = true
  32. end
  33. permissions.push permission_attributes
  34. end
  35. render json: {
  36. tokens: token_list,
  37. permissions: permissions,
  38. }, status: :ok
  39. end
  40. def create
  41. if Setting.get('api_token_access') == false
  42. raise Exceptions::UnprocessableEntity, 'API token access disabled!'
  43. end
  44. if params[:label].blank?
  45. raise Exceptions::UnprocessableEntity, 'Need label!'
  46. end
  47. token = Token.create!(
  48. action: 'api',
  49. label: params[:label],
  50. persistent: true,
  51. user_id: current_user.id,
  52. expires_at: params[:expires_at],
  53. preferences: {
  54. permission: params[:permission]
  55. }
  56. )
  57. render json: {
  58. name: token.name,
  59. }, status: :ok
  60. end
  61. def destroy
  62. token = Token.find_by(action: 'api', user_id: current_user.id, id: params[:id])
  63. raise Exceptions::UnprocessableEntity, 'Unable to find api token!' if !token
  64. token.destroy!
  65. render json: {}, status: :ok
  66. end
  67. end