Class: Dscf::Core::AuthController

Inherits:
ApplicationController show all
Defined in:
app/controllers/dscf/core/auth_controller.rb

Instance Method Summary collapse

Methods included from JsonResponse

#render_error, #render_success, #serialize

Methods included from TokenAuthenticatable

#require_valid_refresh_token, #validate_device_consistency, #validate_token_expiry

Methods included from Authenticatable

#authenticate_user, #authenticate_user!, #current_user, #refresh_token, #sign_in, #sign_out

Instance Method Details

#loginObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/controllers/dscf/core/auth_controller.rb', line 8

def 
  user = AuthService.authenticate_user(params[:email_or_phone], params[:password])

  if user&.valid_for_authentication?
    tokens = (user, request)
    render_success(
      "auth.success.login",
      data: {
        user: user,
        access_token: tokens[:access_token],
        refresh_token: tokens[:refresh_token].refresh_token
      },
      serializer_options: {
        user: {
          serializer: Dscf::Core::UserAuthSerializer
        }
      }
    )
  else
    render_error("auth.errors.invalid_credentials", status: :unauthorized)
  end
end

#logoutObject



61
62
63
64
# File 'app/controllers/dscf/core/auth_controller.rb', line 61

def logout
  sign_out
  render_success("auth.success.logout")
end

#meObject



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'app/controllers/dscf/core/auth_controller.rb', line 66

def me
  render_success(
    "auth.success.me",
    data: {
      user: current_user
    },
    serializer_options: {
      user: {
        serializer: Dscf::Core::UserAuthSerializer
      }
    }
  )
end

#refreshObject



80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'app/controllers/dscf/core/auth_controller.rb', line 80

def refresh
  new_tokens = refresh_token
  if new_tokens
    render_success(
      "auth.success.refresh",
      data: {
        access_token: new_tokens[:access_token]
      }
    )
  else
    render_error("auth.errors.invalid_token", status: :unauthorized)
  end
end

#signupObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/controllers/dscf/core/auth_controller.rb', line 31

def 
  user = User.new(user_params)

  return render_error("auth.errors.missing_email_or_phone") unless user.email.present? || user.phone.present?

  ActiveRecord::Base.transaction do
    if user.save
      assign_default_role(user)
      render_success(
        "auth.success.signup",
        data: {
          user: user
        },
        status: :created,
        serializer_options: {
          user: {
            serializer: Dscf::Core::UserAuthSerializer
          }
        }
      )
    else
      render_error(
        "auth.errors.signup_failed",
        errors: user.errors.full_messages,
        status: :unprocessable_entity
      )
    end
  end
end