Skip to content
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 Management #37

Closed
Show file tree
Hide file tree
Changes from 52 commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
73e8d3c
Solved go version workflow error
PreetinderSinghBadesha Jun 15, 2024
5a3d7b2
Solved router error
PreetinderSinghBadesha Jun 15, 2024
b8ada4f
Merge pull request #5 from DarkCoder26/TestWorkflow
PreetinderSinghBadesha Jun 15, 2024
93cf150
Jwt token and register added in auth
PreetinderSinghBadesha Jun 18, 2024
e379654
Merge pull request #6 from DarkCoder26/Auth
PreetinderSinghBadesha Jun 18, 2024
0669ac8
Merge branch 'MicrosoftStudentChapter:main' into main
PreetinderSinghBadesha Jun 18, 2024
6e09d77
Merge pull request #3 from DarkCoder26/main
JeevantVerma Jun 18, 2024
046ee79
register function updated
PreetinderSinghBadesha Jun 18, 2024
c0e3085
Merge pull request #7 from DarkCoder26/Auth
PreetinderSinghBadesha Jun 18, 2024
b7c731a
Auth Updated
PreetinderSinghBadesha Jun 19, 2024
c793dba
Merge pull request #8 from PreetinderSingh13/Auth
PreetinderSinghBadesha Jun 19, 2024
b8a6c11
added qr generation feature
JeevantVerma Jun 19, 2024
761d9cb
Added dynamic routing
JeevantVerma Jun 19, 2024
9aa77b2
Merge pull request #5 from PreetinderSingh13/main
JeevantVerma Jun 19, 2024
add531b
Login function added
PreetinderSinghBadesha Jun 20, 2024
af5e263
Merge branch 'main' into Auth
PreetinderSinghBadesha Jun 20, 2024
5662ea5
Merge pull request #9 from PreetinderSinghBadesha/Auth
PreetinderSinghBadesha Jun 20, 2024
e6c8fac
React error removed
PreetinderSinghBadesha Jun 20, 2024
6b2d1e1
Merge branch 'main' into ErrorSolved
PreetinderSinghBadesha Jun 20, 2024
1e46b79
Merge pull request #10 from PreetinderSinghBadesha/ErrorSolved
PreetinderSinghBadesha Jun 20, 2024
9dc8e3a
No Expiry Function added
Lakshay229 Jun 22, 2024
eac36b0
removed comments
Lakshay229 Jun 22, 2024
229722d
login page component
priyanshigoyal2801 Jun 23, 2024
993da0a
enhancement of features
priyanshigoyal2801 Jun 23, 2024
68301e1
Merge pull request #40 from priyanshigoyal2801/main
JeevantVerma Jun 24, 2024
757703e
removed container from app.jsx
JeevantVerma Jun 25, 2024
f5969c3
added container in maincontent
JeevantVerma Jun 25, 2024
14a2b9c
completed admin page
JeevantVerma Jun 25, 2024
f5de009
installed necessary dependencies
JeevantVerma Jun 25, 2024
a92f57a
added json data for dynamic input for the admin pages
JeevantVerma Jun 25, 2024
d99095b
administrators component in admin page
JeevantVerma Jun 25, 2024
a74606d
approvals component in admin page added
JeevantVerma Jun 25, 2024
df78293
users component added
JeevantVerma Jun 25, 2024
9e36d19
Merge branch 'main' into test-branch
JeevantVerma Jun 25, 2024
2b1e1ee
Merge pull request #7 from JeevantVerma/test-branch
JeevantVerma Jun 25, 2024
6251625
Merge branch 'front-test' into main
JeevantVerma Jun 25, 2024
20be0ad
Merge pull request #41 from JeevantVerma/main
thakksht Jun 25, 2024
3a5087e
Merge branch 'front-test' into main
Lakshay229 Jun 25, 2024
58274b2
remmoved register function testing code
JeevantVerma Jun 26, 2024
033ec57
removed regiter test from backend
JeevantVerma Jun 26, 2024
5ccb64e
Merge pull request #44 from JeevantVerma/main
JeevantVerma Jun 26, 2024
4d23107
Merge branch 'front-test' into main
JeevantVerma Jun 26, 2024
3c9d2c1
Merge pull request #39 from Lakshay229/main
JeevantVerma Jun 26, 2024
ada71f3
Problem fixed
Lakshay229 Jun 26, 2024
01e82cb
Merge pull request #45 from Lakshay229/front-test
JeevantVerma Jun 26, 2024
62d819a
Auth and cookies added
PreetinderSinghBadesha Jul 4, 2024
dccac19
Fixed positioning of Login page.
JeevantVerma Jul 4, 2024
dd0a14f
Merge branch 'ErrorSolved' of https://github.com/DarkCoder26/Linky in…
PreetinderSinghBadesha Jul 4, 2024
086af5f
Merge pull request #11 from PreetinderSinghBadesha/ErrorSolved
PreetinderSinghBadesha Jul 4, 2024
e7fa57e
Update auth.go
PreetinderSinghBadesha Jul 4, 2024
0ecab01
Merge pull request #48 from JeevantVerma/front-test
PreetinderSinghBadesha Jul 4, 2024
61f538d
Merge branch 'front-test' into main
PreetinderSinghBadesha Jul 4, 2024
ad7dd8c
Update main.go
PreetinderSinghBadesha Jul 4, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added backend/bin/api
Binary file not shown.
2 changes: 1 addition & 1 deletion backend/go-templates/view.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ <h1>All Links</h1>
</div>
</div>
<script type="module">
const password = "04b7ea35d471908eb2ec254dac05e80f7bfed03274d17c2d51b1db0dd1b162cf"
const password = "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5"
let hash = '';
const content = document.querySelector(".content");
while(hash !== password){
Expand Down
13 changes: 13 additions & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,18 @@ require (

require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/labstack/echo/v4 v4.12.0 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/rs/cors v1.11.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/crypto v0.24.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
)
29 changes: 29 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,38 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8=
github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po=
github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
25 changes: 20 additions & 5 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (
"os"

router "github.com/MicrosoftStudentChapter/Link-Generator/pkg/router"

"github.com/gorilla/mux"
"github.com/redis/go-redis/v9"
"github.com/rs/cors"
)

func main() {
Expand All @@ -32,29 +32,44 @@ func main() {

r := mux.NewRouter()

// Define routes
r.HandleFunc("/links/all", router.GetAllLinks).Methods(http.MethodOptions, http.MethodGet)
r.HandleFunc("/login", auth.Login).Methods(http.MethodOptions, http.MethodGet)
r.HandleFunc("/show", auth.ShowUsers).Methods(http.MethodOptions, http.MethodPost)
r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Service is Alive"))
}).Methods(http.MethodOptions, http.MethodGet)
r.HandleFunc("/add-link", router.AddLink).Methods(http.MethodOptions, http.MethodPost)
r.HandleFunc("/{link}", router.HandleRouting).Methods(http.MethodOptions, http.MethodGet)

// Middlewares
r.Use(LoggingMiddleware)
r.Use(mux.CORSMethodMiddleware(r))
r.Use(HandlePreflight)

fmt.Println("Server started at port 4000")
// Configure CORS
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:5173"}, // Change this to your front-end URL
AllowCredentials: true,
AllowedMethods: []string{"GET", "POST"},
AllowedHeaders: []string{"Authorization"},
})

http.ListenAndServe(":4000", r)
handler := c.Handler(r)
fmt.Println("Server started at port 4000")
http.ListenAndServe(":4000", handler)
}

// Middlewares

func HandlePreflight(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:5173") // Change this to your frontend URL
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Credentials", "true")

if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
Expand Down
148 changes: 148 additions & 0 deletions backend/pkg/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package auth

import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"

cookie "github.com/MicrosoftStudentChapter/Link-Generator/pkg/cookies"

"github.com/golang-jwt/jwt"
"golang.org/x/crypto/bcrypt"
)

var jwtKey = []byte(os.Getenv("JWT_SECRET"))
var users = map[string]string{}

type User struct {
ID string
Username string
Password string
}

type Response struct {
Status string `json:"status"`
RedirectUrl string `json:"redirectUrl,omitempty"`
Message string `json:"message,omitempty"`
}

type Claims struct {
Username string "json:username"
jwt.StandardClaims
}

func GenerateTokenAndSetCookies(w http.ResponseWriter, r *http.Request, username string) string {
if username == "" {
http.Error(w, "Username is required", http.StatusBadRequest)
return ""
}

expirationTime := time.Now().Add(30 * time.Minute)
claims := &Claims{
Username: username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
IssuedAt: time.Now().Unix(),
Issuer: "Linky",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
http.Error(w, "Could not generate token", http.StatusInternalServerError)
return ""
}

cookie.SetTokenCookie("access-token", tokenString, expirationTime, w)

return tokenString
}

func ValidateJWT(tokenString string) (string, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
return "", http.ErrBodyNotAllowed
}
return "", err
}
if !token.Valid {
return "", http.ErrBodyNotAllowed
}
return claims.Username, nil
}

func Login(w http.ResponseWriter, r *http.Request) {
username := r.URL.Query().Get("username")
password := r.URL.Query().Get("password")

var loggedInUser *User

users := GetUsers()

for _, user := range users {
if user.Username != username {
continue
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err == nil {
loggedInUser = user
break
}
}

if loggedInUser == nil {
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(Response{Status: "fail", Message: "Invalid Login"})
return
}
tokenString := GenerateTokenAndSetCookies(w, r, username)

if tokenString == "" {
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(Response{Status: "fail", Message: "Token is missing"})
return
}

_, err := ValidateJWT(tokenString)
if err != nil {
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(Response{Status: "fail", Message: err.Error(), RedirectUrl: "http://localhost:5173/error"})
return
}

url := "http://localhost:5173/link-gen"
fmt.Printf("Route Url: " + url)
json.NewEncoder(w).Encode(Response{Status: "success", RedirectUrl: url})
}

func GetUsers() []*User {
password, _ := bcrypt.GenerateFromPassword([]byte("12345"), 8)

return []*User{
{
ID: "1",
Username: "Preet",
Password: string(password),
},
{
ID: "2",
Username: "Jeevant",
Password: string(password),
},
{
ID: "3",
Username: "Akshat",
Password: string(password),
},
}
}

func ShowUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
20 changes: 20 additions & 0 deletions backend/pkg/cookies/cookies.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package cookies

import (
"net/http"
"time"
)

func SetTokenCookie(name, token string, expiration time.Time, w http.ResponseWriter) {
cookie := &http.Cookie{
Name: name,
Value: token,
Expires: expiration,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Secure: false,
}

http.SetCookie(w, cookie)
}
4 changes: 4 additions & 0 deletions backend/pkg/mapping/mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
type Link struct {
Link string `redis:"Link" json:"link"`
ShortURL string `redis:"ShortURL" json:"shortURL"`
Expire string `redis:"Expire" json:"expire"`
}

func AddURL(linkURL string, shortURL string, exp string, ctx context.Context, conn *redis.Client) (Link, error) {
Expand All @@ -21,6 +22,7 @@ func AddURL(linkURL string, shortURL string, exp string, ctx context.Context, co
return Link{
Link: existingMap["Link"],
ShortURL: existingMap["ShortURL"],
Expire: existingMap["Expire"],
}, nil
} else {
return Link{}, fmt.Errorf("shortURL already exists")
Expand All @@ -44,6 +46,7 @@ func AddURL(linkURL string, shortURL string, exp string, ctx context.Context, co
mapping := Link{
Link: linkURL,
ShortURL: shortURL,
Expire: exp,
}
err = conn.HSet(ctx, shortURL, mapping).Err()
if err != nil {
Expand Down Expand Up @@ -78,6 +81,7 @@ func GetAllLinks(ctx context.Context, conn *redis.Client) []Link {
links = append(links, Link{
Link: link["Link"],
ShortURL: link["ShortURL"],
Expire: link["Expire"],
})
}
return links
Expand Down
7 changes: 6 additions & 1 deletion backend/pkg/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ func GetAllLinks(w http.ResponseWriter, r *http.Request) {
var linksData []string
for _, link := range links {
// w.Write([]byte(fmt.Sprintf("%s - %s\n", link.ShortURL, link.Link)))
linksData = append(linksData, fmt.Sprintf("%s - %s\n", link.ShortURL, link.Link))
if link.Expire == "" {
linksData = append(linksData, fmt.Sprintf("%s - %s - %s\n", link.ShortURL, link.Link, "No Expiry"))
} else {

linksData = append(linksData, fmt.Sprintf("%s - %s - %s\n", link.ShortURL, link.Link, link.Expire))
}
}
page.Execute(w, linksData)
}
Expand Down
Loading
Loading