11module Api
22 module V1
3- class SessionsController < Devise ::SessionsController
4- skip_before_action :verify_authenticity_token
5- respond_to :json
3+ class SessionsController < BaseController
4+ skip_before_action :authenticate_user! , only : [ :create , :destroy ]
65
7- private
8-
9- def respond_with ( resource , _opts = { } )
10- render json : {
11- status : { code : 200 , message : 'Logged in successfully.' } ,
12- data : UserSerializer . new ( resource ) . serializable_hash [ :data ] [ :attributes ]
13- } , status : :ok
14- end
15-
16- def respond_to_on_destroy
17- if current_user
6+ def create
7+ user = User . find_by ( email : params . dig ( :user , :email ) )
8+
9+ if user &. valid_password? ( params . dig ( :user , :password ) )
10+ # Generate JWT token using our custom payload method
11+ token_payload = user . jwt_payload
12+ token = JWT . encode ( token_payload , Rails . application . secret_key_base , 'HS256' )
13+
14+ serializer = UserSerializer . new ( user )
15+ user_data = serializer . serializable_hash
16+
1817 render json : {
19- status : 200 ,
20- message : "Logged out successfully."
18+ status : { code : 200 , message : 'Logged in successfully.' } ,
19+ user : user_data [ :data ] ? user_data [ :data ] [ :attributes ] : user_data ,
20+ token : token
2121 } , status : :ok
2222 else
2323 render json : {
24- status : 401 ,
25- message : "Couldn't find an active session."
24+ error : 'Invalid email or password'
2625 } , status : :unauthorized
2726 end
2827 end
28+
29+ def destroy
30+ # For JWT, logout is typically handled client-side by discarding the token
31+ render json : {
32+ status : 200 ,
33+ message : "Logged out successfully."
34+ } , status : :ok
35+ end
2936 end
3037 end
3138end
0 commit comments