Building an E-Commerce Store with Rails and Stripe Checkout: Full T......
rails new jwt_api --api cd jwt_api
# Gemfile gem 'bcrypt', '~> 3.1.7' gem 'jwt'
bundle install
rails generate model User email:string password_digest:string rails db:migrate
# app/models/user.rb class User < ApplicationRecord has_secure_password validates :email, presence: true, uniqueness: true end
rails generate controller Users
# app/controllers/users_controller.rb class UsersController < ApplicationController def create user = User.new(user_params) if user.save render json: { user: user, message: 'User created successfully' }, status: :created else render json: { errors: user.errors.full_messages }, status: :unprocessable_entity end end private def user_params params.require(:user).permit(:email, :password, :password_confirmation) end end
# config/routes.rb Rails.application.routes.draw do resources :users, only: [:create] end
rails generate controller Auth
# app/controllers/auth_controller.rb class AuthController < ApplicationController def login user = User.find_by(email: params[:email]) if user&.authenticate(params[:password]) token = encode_token({ user_id: user.id }) render json: { token: token, message: 'Login successful' }, status: :ok else render json: { errors: 'Invalid email or password' }, status: :unauthorized end end private # Helper method to encode the token def encode_token(payload) JWT.encode(payload, Rails.application.secrets.secret_key_base) end end
# config/routes.rb Rails.application.routes.draw do resources :users, only: [:create] post '/login', to: 'auth#login' end
# app/controllers/application_controller.rb class ApplicationController < ActionController::API before_action :authorized def authorized render json: { message: 'Please log in' }, status: :unauthorized unless logged_in? end private def logged_in? !!current_user end def current_user if decoded_token user_id = decoded_token[0]['user_id'] @current_user ||= User.find_by(id: user_id) end end def decoded_token if auth_header token = auth_header.split(' ')[1] begin JWT.decode(token, Rails.application.secrets.secret_key_base, true, algorithm: 'HS256') rescue JWT::DecodeError nil end end end def auth_header request.headers['Authorization'] end end
rails generate controller Posts
# app/controllers/posts_controller.rb class PostsController < ApplicationController def index posts = Post.all render json: posts end end
# config/routes.rb Rails.application.routes.draw do resources :users, only: [:create] post '/login', to: 'auth#login' resources :posts, only: [:index] end
POST /users { "user": { "email": "[email protected]", "password": "password123", "password_confirmation": "password123" } }
POST /login { "email": "[email protected]", "password": "password123" }
{ "token": "your.jwt.token.here", "message": "Login successful" }
GET /posts Authorization: Bearer your.jwt.token.here
Sign up for free and be the first to get notified about new posts.
No comment