Skip to content

Commit

Permalink
feat: migrated to authentication with cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
ivinayakg committed Mar 1, 2024
1 parent 0acb60d commit 1242772
Show file tree
Hide file tree
Showing 22 changed files with 197 additions and 105 deletions.
6 changes: 6 additions & 0 deletions api/constants/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package constants

type env_type string

const Dev env_type = "development"
const Prod env_type = "prod"
4 changes: 2 additions & 2 deletions api/controllers/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func ResolveURL(w http.ResponseWriter, r *http.Request) {
return
}

go func(r http.Request, url models.URL) {
go func(r *http.Request, url models.URL) {
userAgent := r.Header.Get("User-Agent")
ua := uasurfer.Parse(userAgent)

Expand All @@ -172,7 +172,7 @@ func ResolveURL(w http.ResponseWriter, r *http.Request) {
timestamp := time.Now().Unix()

helpers.Tracker.CaptureRedirectEvent(device, ip, os, referrer, urlId, timestamp)
}(*r, *url)
}(r, *url)

w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
http.Redirect(w, r, url.Destination, http.StatusMovedPermanently)
Expand Down
13 changes: 7 additions & 6 deletions api/controllers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,22 @@ func CallbackSignInWithGoogle(w http.ResponseWriter, r *http.Request) {
return
}

var token *string

if user != nil {
token, _ := utils.CreateJWT(user)
http.Redirect(w, r, fmt.Sprintf(os.Getenv("FRONTEND_AUTH_URL")+"%v", *token), http.StatusSeeOther)
return
token, _ = utils.CreateJWT(user)
} else {
user, err = models.CreateUser(googleProfile["email"].(string), googleProfile["name"].(string), googleProfile["picture"].(string))
if err != nil {
helpers.SendJSONError(w, http.StatusInternalServerError, "Internal Server Error")
return
}
token, _ := utils.CreateJWT(user)
http.Redirect(w, r, fmt.Sprintf(os.Getenv("FRONTEND_AUTH_URL")+"%v", *token), http.StatusSeeOther)
return
token, _ = utils.CreateJWT(user)
}

cookie := utils.CreateAuthCookie(*token)
http.SetCookie(w, cookie)
http.Redirect(w, r, os.Getenv("FRONTEND_URL"), http.StatusSeeOther)
}

func SelfUser(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 2 additions & 0 deletions api/helpers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"time"
)

var ENV string

type ErrorResponse struct {
Error string `json:"error"`
}
Expand Down
3 changes: 1 addition & 2 deletions api/helpers/urls.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ func RemoverDomainError(url string) bool {
}

func BuildUrl(url string) string {
env := os.Getenv("ENV")
if env == "development" {
if ENV == "development" {
return "http://" + os.Getenv("SHORTED_URL_DOMAIN") + url
}
return "https://" + os.Getenv("SHORTED_URL_DOMAIN") + url
Expand Down
4 changes: 3 additions & 1 deletion api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"time"

"github.com/gorilla/mux"
"github.com/ivinayakg/shorte.live/api/constants"
"github.com/ivinayakg/shorte.live/api/controllers"
"github.com/ivinayakg/shorte.live/api/helpers"
"github.com/ivinayakg/shorte.live/api/middleware"
Expand Down Expand Up @@ -56,9 +57,10 @@ func main() {
}

PORT := os.Getenv("PORT")
helpers.ENV = os.Getenv("ENV")

go func() {
if os.Getenv("ENV") != "development" {
if os.Getenv("ENV") == string(constants.Prod) {
return
}
router := createRouter()
Expand Down
25 changes: 20 additions & 5 deletions api/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"strings"

"github.com/ivinayakg/shorte.live/api/constants"
"github.com/ivinayakg/shorte.live/api/helpers"
"github.com/ivinayakg/shorte.live/api/models"
"github.com/ivinayakg/shorte.live/api/utils"
Expand All @@ -19,14 +20,26 @@ const UserAuthKey userAuth = "User"

func Authentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenHeader := strings.Split(r.Header.Get("Authorization"), "Bearer ")
if len(tokenHeader) < 2 {
errMsg := "Authentication error!, Provide valid auth token"
var token string

cookie := utils.GetCookie(r)
if cookie != nil {
token = cookie.Value
} else if helpers.ENV != string(constants.Prod) {
tokenHeader := strings.Split(r.Header.Get("Authorization"), "Bearer ")
if len(tokenHeader) < 2 {
errMsg := "Authentication error!, Provide valid auth token"
helpers.SendJSONError(w, http.StatusForbidden, errMsg)
log.Println(errMsg)
return
}
token = tokenHeader[1]
} else {
errMsg := "Authentication error!, login first"
helpers.SendJSONError(w, http.StatusForbidden, errMsg)
log.Println(errMsg)
return
}
token := tokenHeader[1]

systemNotAvailable := helpers.SystemUnderMaintenance(false)
if systemNotAvailable {
Expand Down Expand Up @@ -54,7 +67,9 @@ func Authentication(next http.Handler) http.Handler {
return
}

user.Token = token
if helpers.ENV != string(constants.Prod) {
user.Token = token
}

c := context.WithValue(r.Context(), UserAuthKey, user)
next.ServeHTTP(w, r.WithContext(c))
Expand Down
3 changes: 2 additions & 1 deletion api/sample.env
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,5 @@ DB_CONFIG_COLLECTION_NAME="config"
SHORTED_URL_DOMAIN="localhost:5100"
FRONTEND_URL_MAINTENANCE="http://localhost:5173/maintenance"
UI_NOT_FOUND_URL="http://localhost:5173/not-found/redirect"
ENV="development"
ENV="development"
COOKIE_NAME="shorte-cookie"
1 change: 1 addition & 0 deletions api/tests/integration/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func setupTests() func() {
helpers.CreateDBInstance()
helpers.RedisSetup()
helpers.SetupTracker(time.Second*2, 5, 0)
helpers.ENV = "test"

go helpers.Tracker.StartFlush()

Expand Down
18 changes: 12 additions & 6 deletions api/tests/integration/system_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ import (
func TestURLSystemAvailability(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, ServerURL+"/system/available", nil)
if err != nil {
t.Fatal(err)
t.Log(err)
t.Fail()
}
testhelper.PutSystemUnderMaintenance(helpers.Redis, false)

// Send the request using the default HTTP client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
t.Log(err)
t.Fail()
}

body := map[string]interface{}{}
Expand All @@ -36,7 +38,8 @@ func TestURLSystemAvailability(t *testing.T) {
func TestURLSystemAvailabilityFail(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, ServerURL+"/system/available", nil)
if err != nil {
t.Fatal(err)
t.Log(err)
t.Fail()
}

testhelper.PutSystemUnderMaintenance(helpers.Redis, true)
Expand All @@ -45,7 +48,8 @@ func TestURLSystemAvailabilityFail(t *testing.T) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
t.Log(err)
t.Fail()
}

body := map[string]interface{}{}
Expand All @@ -59,7 +63,8 @@ func TestURLSystemAvailabilityFail(t *testing.T) {
func TestNotFound(t *testing.T) {
resp, err := RedirecthttpClient.Get(ServerURL + "/" + "something/random")
if err != nil {
t.Fatal(err)
t.Log(err)
t.Fail()
}

notFoundUrl := os.Getenv("UI_NOT_FOUND_URL")
Expand All @@ -71,7 +76,8 @@ func TestNotFound(t *testing.T) {
func TestRedirectHome(t *testing.T) {
resp, err := RedirecthttpClient.Get(ServerURL + "/")
if err != nil {
t.Fatal(err)
t.Log(err)
t.Fail()
}

assert.Equal(t, resp.StatusCode, http.StatusSeeOther, "Excpected status code to be 303")
Expand Down
6 changes: 4 additions & 2 deletions api/tests/integration/tracking_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import (
func TestURLRedirectTracking(t *testing.T) {
resp, err := RedirecthttpClient.Get(ServerURL + "/" + URLFixture.Short)
if err != nil {
t.Fatal(err)
t.Log(err)
t.Fail()
}

destinationURL := URLFixture.Destination
Expand All @@ -29,7 +30,8 @@ func TestURLRedirectTracking(t *testing.T) {
for result == nil {
err := helpers.CurrentDb.RedirectEvent.FindOne(context.Background(), bson.M{"url_id": URLFixture.ID}).Decode(&result)
if err != nil && err != mongo.ErrNoDocuments {
t.Fatal(err)
t.Log(err)
t.Fail()
}
time.Sleep(time.Second * 2)
}
Expand Down
Loading

0 comments on commit 1242772

Please sign in to comment.