Skip to content

Commit

Permalink
Merge pull request #6 from DarkCoder26/Auth
Browse files Browse the repository at this point in the history
Jwt token and register added in auth
  • Loading branch information
PreetinderSinghBadesha authored Jun 18, 2024
2 parents b8ada4f + 93cf150 commit e379654
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 162 deletions.
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
1 change: 1 addition & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ 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
)
2 changes: 2 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ 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/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
Expand Down
6 changes: 5 additions & 1 deletion backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import (
"net/http"
"os"

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

"github.com/gorilla/mux"
"github.com/redis/go-redis/v9"
)
Expand All @@ -33,6 +33,10 @@ func main() {
r := mux.NewRouter()

r.HandleFunc("/links/all", router.GetAllLinks).Methods(http.MethodOptions, http.MethodGet)
r.HandleFunc("/generate/jwt", auth.GenerateJWT).Methods(http.MethodOptions, http.MethodGet)
r.HandleFunc("/validate/jwt", auth.ValidateJWT).Methods(http.MethodOptions, http.MethodGet)
r.HandleFunc("/register", auth.Register).Methods(http.MethodOptions, http.MethodPost)
r.HandleFunc("/show/users", auth.ShowUsers).Methods(http.MethodOptions, http.MethodGet)
r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Service is Alive"))
Expand Down
105 changes: 105 additions & 0 deletions backend/pkg/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package auth

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

"github.com/dgrijalva/jwt-go"
)

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

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

func GenerateJWT(w http.ResponseWriter, r *http.Request) {
username := r.URL.Query().Get("username")
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
}

w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"token": "` + tokenString + `"}`))
// return tokenString
}

func ValidateJWT(w http.ResponseWriter, r *http.Request) {
tokenString := r.URL.Query().Get("token")
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})

if err != nil {
if err == jwt.ErrSignatureInvalid {
http.Error(w, "Invalid token signature", http.StatusUnauthorized)
return
}
http.Error(w, "Invalid token", http.StatusBadRequest)
return
}

if !token.Valid {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"username": claims.Username,
"id": claims.Id,
"issuer": claims.Issuer,
"expiresAt": claims.ExpiresAt,
"issuedAt": claims.IssuedAt,
})

// return claims, nil
}

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

if username == "" || password == "" {
http.Error(w, "Username and password are required", http.StatusBadRequest)
return
}

if _, exists := users[username]; exists {
http.Error(w, "User already exists", http.StatusBadRequest)
return
}

users[username] = password

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "User registered successfully"})
}

func ShowUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
2 changes: 1 addition & 1 deletion frontend/src/Maincontent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const MainContentSection = () => {

const shortenedUrl = generateShortenedUrl(alias);

const link = "https://l.mlsctiet.com"
const link = "http://localhost:4000"

// api call to add link in the backend
const raw = JSON.stringify({
Expand Down
Loading

0 comments on commit e379654

Please sign in to comment.