mirror of
https://github.com/Floriansylvain/RenewCMS.git
synced 2026-08-19 11:43:22 +02:00
Merge pull request #7 from Floriansylvain/feature/JWThttpOnly
Feature/jwt_httpOnly Fix for #6
This commit is contained in:
+16
-6
@@ -10,10 +10,12 @@ import (
|
|||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ginMode string
|
var (
|
||||||
var apiPort string
|
ginMode string
|
||||||
var frontPort string
|
apiPort string
|
||||||
var hostAddress string
|
frontPort string
|
||||||
|
hostAddress string
|
||||||
|
)
|
||||||
|
|
||||||
func initEnvVariables() {
|
func initEnvVariables() {
|
||||||
if godotenv.Load() != nil {
|
if godotenv.Load() != nil {
|
||||||
@@ -35,6 +37,7 @@ func initJWT() {
|
|||||||
|
|
||||||
func initBasicRoutes(r *gin.Engine) {
|
func initBasicRoutes(r *gin.Engine) {
|
||||||
r.POST("/login/", api.AuthMiddleware.LoginHandler)
|
r.POST("/login/", api.AuthMiddleware.LoginHandler)
|
||||||
|
r.POST("/logout/", api.AuthMiddleware.LogoutHandler)
|
||||||
r.GET("/ping/", api.Ping)
|
r.GET("/ping/", api.Ping)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,6 +53,12 @@ func corsMiddleware(c *gin.Context) {
|
|||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func jwtProxyMiddleware(c *gin.Context) {
|
||||||
|
jwtToken, _ := c.Cookie("jwt")
|
||||||
|
c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", jwtToken))
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
|
||||||
func initArticlesRoutes(r *gin.Engine) {
|
func initArticlesRoutes(r *gin.Engine) {
|
||||||
articlesRouter := r.Group("/articles")
|
articlesRouter := r.Group("/articles")
|
||||||
articlesRouter.Use(corsMiddleware, api.AuthMiddleware.MiddlewareFunc())
|
articlesRouter.Use(corsMiddleware, api.AuthMiddleware.MiddlewareFunc())
|
||||||
@@ -63,10 +72,11 @@ func initArticlesRoutes(r *gin.Engine) {
|
|||||||
|
|
||||||
func initGin() {
|
func initGin() {
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
r.Use(corsMiddleware)
|
r.Use(jwtProxyMiddleware, corsMiddleware)
|
||||||
|
|
||||||
if ginMode == "release" {
|
if ginMode == "release" {
|
||||||
gin.SetMode(ginMode)
|
gin.SetMode(ginMode)
|
||||||
|
api.AuthMiddleware.SecureCookie = true
|
||||||
}
|
}
|
||||||
|
|
||||||
initBasicRoutes(r)
|
initBasicRoutes(r)
|
||||||
@@ -77,6 +87,6 @@ func initGin() {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
initEnvVariables()
|
initEnvVariables()
|
||||||
initJWT()
|
|
||||||
initGin()
|
initGin()
|
||||||
|
initJWT()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package api
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -21,11 +22,23 @@ var UsersLocation = database.Location{Database: "gohcms", Collection: "users"}
|
|||||||
var AuthMiddleware, _ = jwt.New(&jwt.GinJWTMiddleware{
|
var AuthMiddleware, _ = jwt.New(&jwt.GinJWTMiddleware{
|
||||||
Realm: "GohCMS",
|
Realm: "GohCMS",
|
||||||
Key: []byte(os.Getenv("APP_JWT_SECRET")),
|
Key: []byte(os.Getenv("APP_JWT_SECRET")),
|
||||||
|
SendCookie: true,
|
||||||
|
CookieHTTPOnly: true,
|
||||||
|
CookieSameSite: http.SameSiteStrictMode,
|
||||||
Timeout: time.Hour,
|
Timeout: time.Hour,
|
||||||
MaxRefresh: time.Hour,
|
MaxRefresh: time.Hour,
|
||||||
|
LoginResponse: JWTLoginResponse,
|
||||||
Authenticator: JWTAuthenticator,
|
Authenticator: JWTAuthenticator,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
func JWTLoginResponse(c *gin.Context, code int, message string, expire time.Time) {
|
||||||
|
if code == http.StatusOK {
|
||||||
|
c.JSON(code, gin.H{"code": code, "message": "Successfully logged in!", "expire": expire.Format(time.RFC3339)})
|
||||||
|
} else {
|
||||||
|
c.JSON(code, gin.H{"code": code, "message": "Something wrong has happened."})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func JWTAuthenticator(c *gin.Context) (interface{}, error) {
|
func JWTAuthenticator(c *gin.Context) (interface{}, error) {
|
||||||
var user = User{}
|
var user = User{}
|
||||||
err := c.BindJSON(&user)
|
err := c.BindJSON(&user)
|
||||||
|
|||||||
@@ -2,13 +2,20 @@
|
|||||||
import { useAuthStore } from '@/stores/AuthStore';
|
import { useAuthStore } from '@/stores/AuthStore';
|
||||||
import { deleteCookie } from '@/utils/cookies';
|
import { deleteCookie } from '@/utils/cookies';
|
||||||
import { RouterLink, useRouter } from 'vue-router'
|
import { RouterLink, useRouter } from 'vue-router'
|
||||||
|
import { baseApiUrl } from "@/utils/api"
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
function logout() {
|
function logout() {
|
||||||
deleteCookie('JWTtoken')
|
deleteCookie('jwt_expire')
|
||||||
deleteCookie('JWTexpire')
|
|
||||||
useAuthStore().clearAll()
|
useAuthStore().clearAll()
|
||||||
|
|
||||||
|
fetch(`${baseApiUrl}/logout`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include'
|
||||||
|
})
|
||||||
|
.catch(error => console.error(error))
|
||||||
|
|
||||||
router.push('/')
|
router.push('/')
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router'
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
import { useAuthStore } from '@/stores/AuthStore'
|
import { useAuthStore } from '@/stores/AuthStore'
|
||||||
import { nextTick } from 'vue'
|
import { nextTick } from 'vue'
|
||||||
import Debug from '@/views/Debug.vue'
|
|
||||||
import Login from '@/views/Login.vue'
|
import Login from '@/views/Login.vue'
|
||||||
import Home from '@/views/Home.vue'
|
import Home from '@/views/Home.vue'
|
||||||
import Articles from '@/views/Articles.vue'
|
import Articles from '@/views/Articles.vue'
|
||||||
@@ -19,14 +18,6 @@ const router = createRouter({
|
|||||||
title: 'GohCMS - Connexion'
|
title: 'GohCMS - Connexion'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: '/debug',
|
|
||||||
name: 'debug',
|
|
||||||
component: Debug,
|
|
||||||
meta: {
|
|
||||||
title: 'GohCMS - Debug'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: '/home',
|
path: '/home',
|
||||||
name: 'home',
|
name: 'home',
|
||||||
@@ -63,13 +54,13 @@ const router = createRouter({
|
|||||||
})
|
})
|
||||||
|
|
||||||
router.beforeEach(async (to, from) => {
|
router.beforeEach(async (to, from) => {
|
||||||
const isTokenValid = useAuthStore().isValid()
|
const isJwtExpired = useAuthStore().isExpired()
|
||||||
if (to.name === 'login') {
|
if (to.name === 'login') {
|
||||||
if (isTokenValid) return {
|
if (!isJwtExpired) return {
|
||||||
name: 'home'
|
name: 'home'
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!isTokenValid) {
|
if (isJwtExpired) {
|
||||||
return {
|
return {
|
||||||
name: 'login',
|
name: 'login',
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,23 +6,18 @@ import { useErrorsStore } from "./ErrorsStore";
|
|||||||
export interface jwtFormat {
|
export interface jwtFormat {
|
||||||
code: number,
|
code: number,
|
||||||
expire: string,
|
expire: string,
|
||||||
token: string
|
message: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useAuthStore = defineStore("AuthStore", () => {
|
export const useAuthStore = defineStore("AuthStore", () => {
|
||||||
const expire = ref('')
|
const expire = ref('')
|
||||||
const token = ref('')
|
|
||||||
|
|
||||||
function clearAll(): void {
|
function clearAll(): void {
|
||||||
expire.value = ''
|
expire.value = ''
|
||||||
token.value = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
function isSet(): boolean {
|
|
||||||
return token.value !== undefined && token.value !== ''
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function isExpired(): boolean {
|
function isExpired(): boolean {
|
||||||
|
if (expire.value === '') return true;
|
||||||
const tokenDate = new Date(expire.value)
|
const tokenDate = new Date(expire.value)
|
||||||
const currentDate = new Date()
|
const currentDate = new Date()
|
||||||
|
|
||||||
@@ -33,20 +28,14 @@ export const useAuthStore = defineStore("AuthStore", () => {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
function isValid(): boolean {
|
|
||||||
return isSet() && !isExpired()
|
|
||||||
}
|
|
||||||
|
|
||||||
function initStore(): void {
|
function initStore(): void {
|
||||||
const JWTtoken = getCookie('JWTtoken')
|
const JWTexpire = getCookie('jwt_expire')
|
||||||
const JWTexpire = getCookie('JWTexpire')
|
if (JWTexpire !== "") {
|
||||||
if (JWTtoken !== "" && JWTexpire !== "") {
|
|
||||||
token.value = JWTtoken
|
|
||||||
expire.value = JWTexpire
|
expire.value = JWTexpire
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
initStore()
|
initStore()
|
||||||
|
|
||||||
return { expire, token, isValid, clearAll }
|
return { expire, clearAll, isExpired}
|
||||||
})
|
})
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export const baseApiUrl = `http://${__APP_ENV__.APP_HOST_ADDRESS}:${__APP_ENV__.APP_API_PORT}`
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { useAuthStore } from "@/stores/AuthStore"
|
import { useAuthStore } from "@/stores/AuthStore"
|
||||||
|
import { baseApiUrl } from "@/utils/api"
|
||||||
|
|
||||||
export interface Article {
|
export interface Article {
|
||||||
titleID: string,
|
titleID: string,
|
||||||
@@ -11,12 +12,10 @@ export interface Article {
|
|||||||
online: boolean
|
online: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const baseURL = `http://${__APP_ENV__.APP_HOST_ADDRESS}:${__APP_ENV__.APP_API_PORT}`
|
|
||||||
|
|
||||||
export async function getArticles(id: string) : Promise<Array<Article>> {
|
export async function getArticles(id: string) : Promise<Array<Article>> {
|
||||||
return await fetch(`${baseURL}/articles/${id}`, {
|
return await fetch(`${baseApiUrl}/articles/${id}`, {
|
||||||
|
credentials: 'include',
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: { "Authorization": `Bearer ${useAuthStore().token}` }
|
|
||||||
})
|
})
|
||||||
.then(result => result.json())
|
.then(result => result.json())
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
@@ -25,9 +24,9 @@ export async function getArticles(id: string) : Promise<Array<Article>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function postArticle(article: Article) : Promise<object> {
|
export async function postArticle(article: Article) : Promise<object> {
|
||||||
return await fetch(`${baseURL}/articles/${article.titleID}`, {
|
return await fetch(`${baseApiUrl}/articles/${article.titleID}`, {
|
||||||
|
credentials: 'include',
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { "Authorization": `Bearer ${useAuthStore().token}` },
|
|
||||||
body: JSON.stringify(article)
|
body: JSON.stringify(article)
|
||||||
})
|
})
|
||||||
.then(result => result.json())
|
.then(result => result.json())
|
||||||
|
|||||||
@@ -1,59 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { useAuthStore } from '@/stores/AuthStore';
|
|
||||||
import { ref } from 'vue';
|
|
||||||
|
|
||||||
const baseURL = `http://${__APP_ENV__.APP_HOST_ADDRESS}:${__APP_ENV__.APP_API_PORT}`
|
|
||||||
const articleID = ref('')
|
|
||||||
|
|
||||||
function getArticles(id?: string) {
|
|
||||||
fetch(`${baseURL}/articles/${id ?? ''}`, {
|
|
||||||
headers: { "Authorization": `Bearer ${useAuthStore().token}` }
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(result => console.log(result))
|
|
||||||
}
|
|
||||||
|
|
||||||
function ping() {
|
|
||||||
fetch(`${baseURL}/ping/`, {
|
|
||||||
headers: { "Authorization": `Bearer ${useAuthStore().token}` }
|
|
||||||
})
|
|
||||||
.then(response => response.json())
|
|
||||||
.then(result => console.log(result))
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="inputs-group">
|
|
||||||
<div>
|
|
||||||
<input type="text" placeholder="article ID" v-model="articleID">
|
|
||||||
<button class="button-primary" @click="getArticles(articleID)">get article</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="buttons-group">
|
|
||||||
<button class="button-primary" @click="ping()">ping</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.editor {
|
|
||||||
position: relative;
|
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.buttons-group,
|
|
||||||
.inputs-group {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 8px;
|
|
||||||
margin: 32px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.inputs-group {
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.inputs-group div {
|
|
||||||
flex-direction: row;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useAuthStore, type jwtFormat } from '@/stores/AuthStore';
|
import { useAuthStore, type jwtFormat } from '@/stores/AuthStore';
|
||||||
import { useErrorsStore } from '@/stores/ErrorsStore';
|
import { useErrorsStore } from '@/stores/ErrorsStore';
|
||||||
|
import { baseApiUrl } from '@/utils/api';
|
||||||
import { setCookie } from '@/utils/cookies';
|
import { setCookie } from '@/utils/cookies';
|
||||||
import { ref, type Ref } from 'vue';
|
import { ref, type Ref } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
import { useRouter } from 'vue-router';
|
||||||
@@ -20,12 +21,7 @@ function updateJWTcookies(JWTdata: jwtFormat): void {
|
|||||||
cookieExpire.setDate(cookieExpire.getDate() + 1)
|
cookieExpire.setDate(cookieExpire.getDate() + 1)
|
||||||
|
|
||||||
setCookie({
|
setCookie({
|
||||||
key: 'JWTtoken',
|
key: 'jwt_expire',
|
||||||
value: JWTdata.token,
|
|
||||||
expire: cookieExpire.toString()
|
|
||||||
})
|
|
||||||
setCookie({
|
|
||||||
key: 'JWTexpire',
|
|
||||||
value: JWTdata.expire,
|
value: JWTdata.expire,
|
||||||
expire: cookieExpire.toString()
|
expire: cookieExpire.toString()
|
||||||
})
|
})
|
||||||
@@ -43,14 +39,14 @@ function jwtHandler(apiResponse: jwtFormat): void {
|
|||||||
}
|
}
|
||||||
updateJWTcookies(apiResponse)
|
updateJWTcookies(apiResponse)
|
||||||
disableErrors()
|
disableErrors()
|
||||||
authStore.token = apiResponse.token
|
|
||||||
authStore.expire = apiResponse.expire
|
authStore.expire = apiResponse.expire
|
||||||
isTokenOK.value = true
|
isTokenOK.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
function login(email: string, password: string): void {
|
function login(email: string, password: string): void {
|
||||||
fetch(`http://${__APP_ENV__.APP_HOST_ADDRESS}:${__APP_ENV__.APP_API_PORT}/login/`, {
|
fetch(`${baseApiUrl}/login/`, {
|
||||||
method: "POST",
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
email: email,
|
email: email,
|
||||||
password: password
|
password: password
|
||||||
|
|||||||
Reference in New Issue
Block a user