Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
25 changes: 25 additions & 0 deletions apiserver/frontend/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"embed"
"io/fs"
"net/http"
"strings"

config "dkhalife.com/tasks/core/config"
"github.com/gin-gonic/gin"
Expand All @@ -12,6 +13,8 @@ import (
//go:embed dist
var embeddedFiles embed.FS

var publicPaths = []string{"/login", "/privacy"}

type Handler struct {
ServeFrontend bool
}
Expand All @@ -29,6 +32,15 @@ func Routes(router *gin.Engine, h *Handler) {
}
}

func isPublicPath(path string) bool {
for _, p := range publicPaths {
if path == p || strings.HasPrefix(path, p+"/") {
return true
}
}
return false
Comment thread
dkhalife marked this conversation as resolved.
}

func staticMiddleware(root string) gin.HandlerFunc {
fileServer := http.FileServer(getFileSystem(root))

Expand All @@ -42,10 +54,23 @@ func staticMiddleware(root string) gin.HandlerFunc {

}
}
const authCookieName = "tw_auth"

func staticMiddlewareNoRoute(root string) gin.HandlerFunc {
fileServer := http.FileServer(getFileSystem(root))

return func(c *gin.Context) {
if !isPublicPath(c.Request.URL.Path) {
if _, err := c.Cookie(authCookieName); err != nil {
target := "/login?return_to=" + c.Request.URL.Path
if q := c.Request.URL.RawQuery; q != "" {
target += "&" + q
}
c.Redirect(http.StatusFound, target)
return
}
}

c.Request.URL.Path = "/"
fileServer.ServeHTTP(c.Writer, c.Request)
}
Expand Down
20 changes: 16 additions & 4 deletions frontend/src/utils/msal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const doInitializeMsal = async () => {
auth: {
clientId: authConfig.client_id,
authority: `https://login.microsoftonline.com/${authConfig.tenant_id}`,
redirectUri: window.location.origin,
redirectUri: `${window.location.origin}/login`,
},
cache: {
cacheLocation: 'localStorage',
Expand Down Expand Up @@ -92,16 +92,25 @@ export const hasCachedAccounts = async (): Promise<boolean> => {
return pca.getAllAccounts().some(a => a.tenantId === authConfig?.tenant_id)
}

const AUTH_COOKIE = 'tw_auth'

const setAuthCookie = () => {
document.cookie = `${AUTH_COOKIE}=1; path=/; SameSite=Strict; max-age=31536000`
}

const clearAuthCookie = () => {
document.cookie = `${AUTH_COOKIE}=; path=/; SameSite=Strict; max-age=0`
}

export const loginSilently = async (): Promise<boolean> => {
if (!authConfig?.enabled || !pcaPromise) return true
const pca = await pcaPromise
try {
const account = ensureActiveAccount(pca)
cachedAuthResult = await pca.acquireTokenSilent({ scopes: getScopes(), account })
setAuthCookie()
return true
} catch {
// acquireTokenSilent failed — try ssoSilent as a fallback (works when browser
// still has a valid session cookie for login.microsoftonline.com)
try {
const account = pca.getActiveAccount() ?? pca.getAllAccounts().find(a => a.tenantId === authConfig?.tenant_id)
cachedAuthResult = await pca.ssoSilent({
Expand All @@ -111,8 +120,10 @@ export const loginSilently = async (): Promise<boolean> => {
if (cachedAuthResult.account) {
pca.setActiveAccount(cachedAuthResult.account)
}
setAuthCookie()
return true
} catch {
clearAuthCookie()
return false
}
}
Expand All @@ -131,11 +142,12 @@ export const acquireAccessToken = async (): Promise<string> => {
}

export const logout = async () => {
clearAuthCookie()
if (!authConfig?.enabled || !pcaPromise) {
window.location.href = '/'
return
}
const pca = await pcaPromise
cachedAuthResult = null
await pca.logoutRedirect({ postLogoutRedirectUri: window.location.origin })
await pca.logoutRedirect({ postLogoutRedirectUri: `${window.location.origin}/login` })
}
9 changes: 7 additions & 2 deletions frontend/src/views/Authorization/LoginView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import React from 'react'
import { Link } from 'react-router-dom'
import { hasCachedAccounts, initializeMsal, loginSilently, loginWithRedirect } from '@/utils/msal'
import { setTitle } from '@/utils/dom'
import { NavigationPaths, WithNavigate } from '@/utils/navigation'
import { getQuery, NavigationPaths, WithNavigate } from '@/utils/navigation'
import { connect } from 'react-redux'
import { AppDispatch } from '@/store/store'
import { pushStatus } from '@/store/statusSlice'
Expand All @@ -31,12 +31,17 @@ class LoginViewImpl extends React.Component<LoginViewProps, LoginViewState> {
this.state = { authReady: false }
}

private getReturnPath = (): string => {
const returnTo = getQuery('return_to')
return returnTo || NavigationPaths.HomeView()
}

async componentDidMount(): Promise<void> {
setTitle('Login')
await initializeMsal()
const silentOk = await loginSilently()
if (silentOk) {
this.props.navigate(NavigationPaths.HomeView())
this.props.navigate(this.getReturnPath())
return
}
try {
Expand Down
Loading