Skip to content
This repository has been archived by the owner on Dec 13, 2024. It is now read-only.

Commit

Permalink
feat/fix: adds email auth
Browse files Browse the repository at this point in the history
  • Loading branch information
zakhaev26 committed Feb 24, 2024
1 parent e8bc33d commit 22c02df
Show file tree
Hide file tree
Showing 10 changed files with 123 additions and 13 deletions.
15 changes: 10 additions & 5 deletions auth/internal/handlers/signup_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"time"

"github.com/golang-jwt/jwt"
"github.com/p-society/gc-server/auth/internal"
"github.com/p-society/gc-server/auth/internal/utils"
"github.com/p-society/gc-server/auth/pkg/security"
model "github.com/p-society/gc-server/schemas/pkg/models"
Expand All @@ -17,23 +18,22 @@ func SignUpHandler(w http.ResponseWriter, r *http.Request) {
var p model.Player

w.Header().Set("Content-Type", "application/json")

err := json.NewDecoder(r.Body).Decode(&p)
defer r.Body.Close()

if err != nil {
json.NewEncoder(w).Encode(err)
return
}
err = p.Valid()

err = p.Valid()
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
})
return
}

fmt.Println("p.Email @signup", p.Email)
err = utils.IsUniqueInDB(p.Email)
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{
Expand All @@ -42,16 +42,21 @@ func SignUpHandler(w http.ResponseWriter, r *http.Request) {
return
}

// TODO:Send OTP Mail

p.StandardClaims = jwt.StandardClaims{
IssuedAt: time.Now().Unix(),
ExpiresAt: time.Now().Add(5 * time.Minute).Unix(),
}
// TODO : Check password to be

p.OTP = utils.GenerateOTP(6)
fmt.Println(p.OTP)

if err := internal.SendEmail(&p); err != nil {
json.NewEncoder(w).Encode(err.Error())
}

hashedPass, err := bcrypt.GenerateFromPassword([]byte(p.Password), 10)

if err != nil {
panic(err)
}
Expand Down
59 changes: 59 additions & 0 deletions auth/internal/render_engine.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package internal

func RenderEngine(OTP int) string {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grand Championship Sports Fest OTP Verification</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f7f7f7;
line-height: 1.6;
}
.container {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1, p {
margin: 0 0 20px;
}
.btn {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: #fff;
text-decoration: none;
border-radius: 5px;
}
.btn:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<p>In order to finalize your participation and confirm your registration for the Grand Championship Sports Fest, we require you to undergo a one-time verification process. This verification will be conducted through the use of a unique One-Time Password (OTP) sent to your registered email address.</p>
<p><strong>This is your OTP: ` + string(OTP) + `</strong></p>
<p>Please note that this OTP is valid for 5 minutes. Kindly complete the verification process within this timeframe to ensure successful registration.</p>
<!-- Footer -->
<div style="margin-top: 20px; text-align: center;">
<img src="https://media.licdn.com/dms/image/C510BAQFpxyHUatuOvA/company-logo_200_200/0/1630569018702/p_soc_logo?e=1717027200&v=beta&t=8zgvl2h1i6ORVp9JQTbhG-lXwFVLuif-v1V0CnJp6Hc" alt="P-Society IIIT-Bh Logo" style="max-width: 100px;">
<p>Open Source Software Wing, Programming Society, IIIT-Bh</p>
</div>
</div>
</body>
</html>
`
}
1 change: 1 addition & 0 deletions auth/internal/router/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ func AuthRouter() *mux.Router {
r.HandleFunc("/v0/auth/callback/signup", handlers.CallbackVerification).Methods("post")
r.HandleFunc("/v0/auth/login", handlers.Login).Methods("POST")
return r

}
38 changes: 38 additions & 0 deletions auth/internal/sendMail.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package internal

import (
"bytes"
"encoding/json"
"fmt"
"net/http"

model "github.com/p-society/gc-server/schemas/pkg/models"
)

func SendEmail(p *model.Player) error {
var (
url = "http://localhost:6969/v0/mails"
requestBody = map[string]interface{}{
"subject": "Grand Championship Player Verification",
"content": RenderEngine(p.OTP),
"to": []string{p.Email},
}
)

requestBodyBytes, err := json.Marshal(requestBody)
if err != nil {
return fmt.Errorf("error encoding JSON: %v", err)
}

resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBodyBytes))
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected response status: %s", resp.Status)
}

return nil
}
5 changes: 0 additions & 5 deletions auth/pkg/security/rbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ import (
"github.com/p-society/gc-server/auth/internal/utils"
)

// RoleGuard is a middleware for role-based access control
type RoleGuard struct {
AllowedRoles []string
Handler http.Handler
}

// ServeHTTP implements the http.Handler interface for RoleGuard
func (rg *RoleGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var (
token string
Expand All @@ -28,18 +26,15 @@ func (rg *RoleGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) {

p := ParseAccessToken(token)

// Check if user's role is allowed
if !contains(rg.AllowedRoles, p.Role) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
return
}

// Call the next handler in the chain
rg.Handler.ServeHTTP(w, r)
}

// contains checks if a string is present in a slice of strings
func contains(roles []string, role string) bool {
for _, r := range roles {
if r == role {
Expand Down
8 changes: 8 additions & 0 deletions auth/pkg/security/rbac.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Protected route with role-based access control

```
r.Handle("/v0/auth/login", &security.RoleGuard{
AllowedRoles: []string{security.RoleSuperAdmin, security.RoleAdmin},
Handler: http.HandlerFunc(handlers.Login),
}).Methods("POST")
```
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
)

require (
github.com/a-h/templ v0.2.543 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/a-h/templ v0.2.543 h1:8YyLvyUtf0/IE2nIwZ62Z/m2o2NqwhnMynzOL78Lzbk=
github.com/a-h/templ v0.2.543/go.mod h1:jP908DQCwI08IrnTalhzSEH9WJqG/Q94+EODQcJGFUA=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
Expand All @@ -6,6 +8,7 @@ github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
Expand Down
6 changes: 3 additions & 3 deletions mail/pkg/sender.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
package sender

import (
"fmt"
"os"

mailConfig "github.com/p-society/gc-server/mail/internal"
"github.com/p-society/gc-server/mail/internal/models"
)

func SendMail(subject string, content string, to []string) error {

fmt.Println("called,to = ", to)
senderName := os.Getenv("EMAIL_SENDER_NAME")
senderAddress := os.Getenv("EMAIL_SENDER_ADDRESS")
senderPassword := os.Getenv("EMAIL_SENDER_PASSWORD")

fmt.Println("sn = ",senderName)
sender := mailConfig.NewGmailSender(senderName, senderAddress, senderPassword)

paramInstance := models.MailingParams{
Subject: subject,
Content: content,
Expand Down
Empty file added sendMail.txt
Empty file.

0 comments on commit 22c02df

Please sign in to comment.