-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
User Authentication and Authorization using JWT #2
Open
sagar23sj
wants to merge
51
commits into
development
Choose a base branch
from
User_Operations
base: development
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 44 commits
Commits
Show all changes
51 commits
Select commit
Hold shift + click to select a range
7670aa4
Updated Migration For User Table
sagar23sj 986fe29
Added GetUserByMobile method in Storer Interface
sagar23sj 39734b4
Called GetUserByMobile in Storer Interface
sagar23sj adcd53d
Updated Users Table
sagar23sj 3560764
Updated User Table
sagar23sj 51f2149
Added Routes and JWT Middleware
sagar23sj 1f192ce
Added JWT Token Generate and Logout Methods
sagar23sj 568b0c0
Added Necessary Comments
sagar23sj 15c11c6
Added Necessary Comments
sagar23sj 967cd62
Imported New Libraries
sagar23sj dbb75ae
Added Methods to Fetch JWT SecretKey and ExpirationTime
sagar23sj dcbaa01
Added getUserHandler
sagar23sj b7e61b8
Added Necessary Comments
sagar23sj 31a01aa
Added Necessary methods for user sql operations
sagar23sj 52edc97
Defined Necessary SQL methods in Interface
sagar23sj f142949
File for Handling Error Messages
sagar23sj ff41a90
Added Database Migrations for Handling Blaclisted Tokens
sagar23sj 6744375
Created file for managing user_blacklisted_tokens methods
sagar23sj 931af3e
Added Necessary Comments
sagar23sj 4f9b70d
Updated CreateBlacklistedToken
sagar23sj 166d880
Added Necessary Comments
sagar23sj 54d9345
Updated jwtMiddleware function
sagar23sj 80cebad
Added Necessary Comments
sagar23sj f8d75a8
Updated CheckBlacklistedToken Function
sagar23sj 4027941
Refactored JWTMiddleWare function and added necessary comments
sagar23sj a5e96ed
Refactored the userLoginHandle and userLogoutHandle function and adde…
sagar23sj e3152fe
Added necessary comments
sagar23sj 8ee4898
Removed Unused Error Messages
sagar23sj d1ba6e5
Handled Errors uding Messages From apperrors file
sagar23sj 97b3619
Handled Error Messages from apperrors file
sagar23sj 3dbe5a0
Changes in Commenting
sagar23sj 6fb9221
Changes in Commenting
sagar23sj 08589e0
Changes in Error Handling for GenerateJWTToken
sagar23sj 340650c
Removed NOT NULL constraint from Mobile from User
sagar23sj 8d13a62
Added Regex for id validation in routes
sagar23sj 944ea05
Added Necessary Error Handling
sagar23sj c2073ab
Added necessary Error Handling
b36411e
Added Json responce object as AuthToken
9e705dd
Updated constraint from user migration
c8c5758
Changes in route and jwtMiddleWare function
sagar23sj 84eebc6
Added getDataFromToken function and updated userLogoutHandler
sagar23sj faa0d43
Updated user_id fteching in getUserHandler function
sagar23sj 9319a24
Removed Unnecessary Comments
sagar23sj cbb000f
Handled CORS
sagar23sj 69de9e3
Removed Unnecessary Error Handling
3f0adae
Updated Response Body Structure
5c1a4ec
Fixed minor error
8545a3c
Updated Setter And Getter Method For Header
6e7a6f9
Updated User struct
d28894b
Added Necessary Error Handling
2e3fa5a
Changed Identifier err1 To err
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package apperrors | ||
|
||
import ( | ||
"encoding/json" | ||
"errors" | ||
l "github.com/sirupsen/logrus" | ||
"net/http" | ||
) | ||
|
||
// ErrorStruct - struct used to convert error messages into required JSON format | ||
type ErrorStruct struct { | ||
Message string `json:"message,omitempty"` //Error Message | ||
Status int `json:"status,omitempty"` //HTTP Response status code | ||
} | ||
|
||
// Error - prints out an error | ||
func Error(appError error, msg string, triggeringError error) { | ||
l.WithFields(l.Fields{"appError": appError, "message": msg}).Error(triggeringError) | ||
} | ||
|
||
// Warn - for warnings | ||
func Warn(appError error, msg string, triggeringError error) { | ||
l.WithFields(l.Fields{"appError": appError, "message": msg}).Warn(triggeringError) | ||
} | ||
|
||
// JSONError - This function writes out an error response with the status | ||
// header passed in | ||
func JSONError(rw http.ResponseWriter, status int, err error) { | ||
|
||
errObj := ErrorStruct{ | ||
Message: err.Error(), | ||
Status: status, | ||
} | ||
|
||
errJSON, err := json.Marshal(&errObj) | ||
if err != nil { | ||
Warn(err, "Error in AppErrors marshalling JSON", err) | ||
} | ||
rw.WriteHeader(status) | ||
rw.Header().Add("Content-Type", "application/json") | ||
rw.Write(errJSON) | ||
return | ||
} | ||
|
||
// ErrRecordNotFound - for when a database record isn't found | ||
var ErrRecordNotFound = errors.New("Database record not found") | ||
|
||
// ErrInvalidToken - used when a JSON Web Token ("JWT") cannot be validated | ||
// by the JWT library | ||
var ErrInvalidToken = errors.New("Invalid Token") | ||
|
||
// ErrSignedString - failed to sign the token string | ||
var ErrSignedString = errors.New("Failed to sign token string") | ||
|
||
// ErrMissingAuthHeader - When the HTTP request doesn't contain an 'Authorization' header | ||
var ErrMissingAuthHeader = errors.New("Missing Auth header") | ||
|
||
// ErrJSONParseFail - If json.Unmarshal or json.Marshal returns an error | ||
var ErrJSONParseFail = errors.New("Failed to parse JSON response (likely not valid JSON)") | ||
|
||
// ErrNoSigningKey - there isn't a signing key defined in the app configuration | ||
var ErrNoSigningKey = errors.New("no JWT signing key specified; cannot authenticate users. Define JWT_SECRET in application.yml and restart") | ||
|
||
// ErrFailedToCreate - Record Creation Failed | ||
var ErrFailedToCreate = errors.New("Failed to create database record") | ||
|
||
// ErrUnknown - Generic Error For Unknown Errors | ||
var ErrUnknown = errors.New("unknown/unexpected error has occurred") |
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
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,49 @@ | ||
package db | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"time" | ||
|
||
logger "github.com/sirupsen/logrus" | ||
) | ||
|
||
//BlacklistedToken - struct representing a token to be blacklisted (logout) | ||
type BlacklistedToken struct { | ||
ID int `db:"id" json:"id"` | ||
UserID float64 `db:"user_id" json:"user_id"` | ||
Token string `db:"token" json:"token"` | ||
ExpirationDate time.Time `db:"expiration_date" json:"expiration_date"` | ||
} | ||
|
||
const ( | ||
insertBlacklistedToken = `INSERT INTO user_blacklisted_tokens | ||
(user_id, token, expiration_date) | ||
VALUES ($1, $2, $3)` | ||
) | ||
|
||
//CreateBlacklistedToken function to insert the blacklisted token in database | ||
func (s *pgStore) CreateBlacklistedToken(ctx context.Context, token BlacklistedToken) (err error) { | ||
_, err = s.db.Exec(insertBlacklistedToken, token.UserID, token.Token, token.ExpirationDate) | ||
|
||
if err != nil { | ||
errMsg := fmt.Sprintf("Error inserting the blacklisted token for user with id %v", token.UserID) | ||
logger.WithField("err", err.Error()).Error(errMsg) | ||
return | ||
} | ||
return | ||
} | ||
|
||
//CheckBlacklistedToken function to check if token is blacklisted earlier | ||
func (s *pgStore) CheckBlacklistedToken(ctx context.Context, token string) (bool, int) { | ||
|
||
var userID int | ||
query1 := fmt.Sprintf("SELECT user_id FROM user_blacklisted_tokens WHERE token='%s'", token) | ||
err := s.db.QueryRow(query1).Scan(&userID) | ||
|
||
if err != nil { | ||
logger.WithField("err", err.Error()).Error("Either Query Failed or No Rows Found") | ||
return false, -1 | ||
} | ||
return true, userID | ||
} |
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
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,4 +1,13 @@ | ||
CREATE TABLE users ( | ||
name text, | ||
age integer | ||
); | ||
CREATE TABLE IF NOT EXISTS users ( | ||
id SERIAL NOT NULL PRIMARY KEY, | ||
first_name VARCHAR(255) NOT NULL, | ||
last_name VARCHAR(255), | ||
email VARCHAR(255) NOT NULL UNIQUE, | ||
mobile VARCHAR(20), | ||
country VARCHAR(100), | ||
state VARCHAR(100), | ||
city VARCHAR(100), | ||
address TEXT, | ||
password TEXT, | ||
created_at TIMESTAMP DEFAULT (NOW() AT TIME ZONE 'UTC') | ||
); |
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 @@ | ||
DROP TABLE IF EXISTS user_blacklisted_tokens; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we use
time.Time
instead of string?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually we are thinking of removing it since we are neither accepting it from the frontend nor we are sending it back.