-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
20 changed files
with
759 additions
and
468 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
class Api::V1::AuthenticationController < ApplicationController | ||
before_action :authenticate_user, only: [:current_user] | ||
|
||
def sign_in | ||
unless params[:email] && params[:password] | ||
return render json: { success: false, error: 'Invalid request! Missing information.' }, | ||
status: :bad_request | ||
end | ||
|
||
user = User.find_by(email: params[:email]) | ||
if user&.authenticate(params[:password]) | ||
user.password_digest = nil | ||
token = JwtToken.sign({ user_id: user.id }) | ||
render json: { | ||
success: true, | ||
data: { | ||
user:, | ||
accessToken: token | ||
} | ||
}, status: :ok | ||
else | ||
render json: { success: false, error: 'Invalid email or password' }, status: :unauthorized | ||
end | ||
end | ||
|
||
def current_user | ||
render json: { success: true, data: @current_user }, status: :ok | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
class Api::V1::UsersController < ApplicationController | ||
before_action :authenticate_user, except: :create | ||
load_and_authorize_resource | ||
rescue_from ActiveRecord::RecordNotFound, with: :user_not_found | ||
before_action :set_user, only: %i[show update destroy] | ||
|
||
# GET /users | ||
def index | ||
@users = User.all | ||
|
||
render json: @users.as_json(except: [:password_digest]) | ||
end | ||
|
||
# GET /users/1 | ||
def show | ||
render json: @user.as_json(except: [:password_digest]) | ||
end | ||
|
||
# POST /users | ||
def create | ||
user_params[:role] = 'user' | ||
|
||
@user = User.new(user_params) | ||
|
||
if @user.save | ||
render json: @user.as_json(except: [:password_digest]), status: :created | ||
else | ||
render json: @user.errors, status: :unprocessable_entity | ||
end | ||
end | ||
|
||
# PATCH/PUT /users/1 | ||
def update | ||
if @user.update(user_params) | ||
render json: @user.as_json(except: [:password_digest]) | ||
else | ||
render json: @user.errors, status: :unprocessable_entity | ||
end | ||
end | ||
|
||
# DELETE /users/1 | ||
def destroy | ||
@user.destroy | ||
|
||
render json: { message: 'User deleted successfully' }, status: :no_content | ||
end | ||
|
||
private | ||
|
||
# Use callbacks to share common setup or constraints between actions. | ||
def user_not_found | ||
render json: { error: "No user with id #{params[:id]}" }, status: :not_found | ||
end | ||
|
||
def set_user | ||
@user = User.find(params[:id]) | ||
end | ||
|
||
# Only allow a list of trusted parameters through. | ||
def user_params | ||
params.require(:user).permit(:name, :email, :role, :password, :password_confirmation, :avatar) | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,39 @@ | ||
class ApplicationController < ActionController::API | ||
include JwtToken | ||
include CanCan::ControllerAdditions | ||
|
||
rescue_from CanCan::AccessDenied, with: :unauthorized_user | ||
def not_found | ||
render json: { error: 'Route not found' }, status: :not_found | ||
end | ||
|
||
protected | ||
|
||
def authenticate_user | ||
header = request.headers['Authorization'] | ||
token = header.split.last if header | ||
|
||
begin | ||
@decoded = JwtToken.verify(token) | ||
|
||
curr_time = Time.now | ||
if curr_time > @decoded[:exp] | ||
return render json: { success: false, error: 'Invalid token!' }, | ||
status: :unauthorized | ||
end | ||
|
||
@current_user = User.find(@decoded[:user_id]) | ||
@current_user.password_digest = nil | ||
rescue ActiveRecord::RecordNotFound => e | ||
render json: { success: false, error: e.message }, status: :unauthorized | ||
rescue JWT::DecodeError => _e | ||
render json: { success: false, error: 'Invalid token!' }, status: :unauthorized | ||
end | ||
end | ||
|
||
attr_reader :current_user | ||
|
||
def unauthorized_user(_exception) | ||
render json: { success: false, error: 'Unauthorize access denied!' }, status: :forbidden | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
require 'jwt' | ||
|
||
module JwtToken | ||
extend ActiveSupport::Concern | ||
SECRET_KEY = Rails.application.secrets.access_token_key.to_s || 'this is a demo key' | ||
|
||
def self.sign(payload, exp = 1.days.from_now) | ||
payload[:exp] = exp.to_i | ||
JWT.encode(payload, SECRET_KEY) | ||
end | ||
|
||
def self.verify(token) | ||
decoded = JWT.decode(token, SECRET_KEY)[0] | ||
HashWithIndifferentAccess.new decoded | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
class Ability | ||
include CanCan::Ability | ||
|
||
def initialize(user) | ||
user ||= User.new # guest user (not logged in) | ||
if user.admin? | ||
can :manage, :all | ||
can :manage, User | ||
else | ||
can :create, User | ||
can :show, User, id: user.id | ||
can :update, User, id: user.id | ||
can :destroy, User, id: user.id | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,28 @@ | ||
class User < ApplicationRecord | ||
# Include default devise modules. Others available are: | ||
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable | ||
devise :database_authenticatable, :registerable, | ||
:recoverable, :rememberable, :validatable | ||
has_many :property | ||
|
||
validates :password, confirmation: true | ||
validates :name, presence: true | ||
validates :avatar, presence: true | ||
validates :role, inclusion: { in: %w[user admin] } | ||
validates :name, presence: { message: "Name can't be blank" }, | ||
length: { maximum: 50, message: 'Name is too long (maximum is %<count>s characters)' } | ||
validates :email, presence: { message: "Email can't be blank" }, | ||
length: { maximum: 255, message: 'Email is too long (maximum is %<count>s characters)' }, | ||
format: { with: URI::MailTo::EMAIL_REGEXP, message: 'Email format is invalid' }, | ||
uniqueness: { case_sensitive: false, message: 'Email has already been taken' } | ||
validates :role, inclusion: { in: %w[user admin], message: "Role must be 'user' or 'admin'" } | ||
|
||
has_secure_password | ||
|
||
validates :password, presence: { message: "Password can't be blank" }, on: :create | ||
|
||
validate :password_confirmation_matches_password, on: :create | ||
|
||
def password_confirmation_matches_password | ||
return unless password_confirmation != password | ||
|
||
errors.add(:password_confirmation, "Password confirmation doesn't match password") | ||
end | ||
|
||
def admin? | ||
role == 'admin' | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.