github.com/blend/go-sdk@v1.20220411.3/examples/web/auth/main.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package main 9 10 import ( 11 "context" 12 "fmt" 13 "strings" 14 15 "github.com/blend/go-sdk/graceful" 16 "github.com/blend/go-sdk/logger" 17 "github.com/blend/go-sdk/web" 18 ) 19 20 /* 21 This example is meant to illustrate the bare minimum required to implement an authenticated web app. 22 It is meant to be extended considerably, and is not secure as currently formed. 23 You should investigate specific authentication mechanisms like oauth to do the actual authentication. 24 Caveat; this will only work if you are deploying a single instance of the app. 25 */ 26 27 func main() { 28 app := web.MustNew( 29 web.OptLog(logger.All()), 30 web.OptAuth(web.NewLocalAuthManager()), 31 ) 32 33 app.ServeStaticCached("/cached", []string{"_static"}, web.SessionMiddleware(func(ctx *web.Ctx) web.Result { 34 return web.Text.NotAuthorized() 35 })) 36 app.ServeStatic("/static", []string{"_static"}, web.SessionMiddleware(func(ctx *web.Ctx) web.Result { 37 return web.Text.NotAuthorized() 38 })) 39 app.ServeStatic("/static_unauthed", []string{"_static"}) 40 41 app.Auth.ValidateHandler = func(_ context.Context, session *web.Session) error { 42 if session.UserID == "example-string" { 43 return fmt.Errorf("example-string isn't allowed here") 44 } 45 return nil 46 } 47 app.Auth.LoginRedirectHandler = web.PathRedirectHandler("/login") 48 49 app.Views.AddLiterals(`{{ define "login" }}<a href="/login/user_valid">Login Valid</a><br/><a href="/login/user_notvalid">Login Invalid</a>{{end}}`) 50 app.GET("/login", func(r *web.Ctx) web.Result { 51 return r.Views.View("login", nil) 52 }) 53 54 app.GET("/login/:userID", func(r *web.Ctx) web.Result { 55 if r.Session != nil { 56 r.App.Log.Debugf("already logged in, redirecting") 57 return web.RedirectWithMethodf("GET", "/") 58 } 59 60 userID, _ := r.Param("userID") 61 if !strings.HasSuffix(userID, "_valid") { //maximum security 62 return web.Text.NotAuthorized() 63 } 64 _, err := r.Auth.Login(userID, r) 65 if err != nil { 66 return web.Text.InternalError(err) 67 } 68 return web.Text.Result("Logged In") 69 }, web.SessionAware) 70 71 app.GET("/logout", func(r *web.Ctx) web.Result { 72 if r.Session == nil { 73 return web.Text.Result("Weren't logged in anyway.") 74 } 75 err := r.Auth.Logout(r) 76 if err != nil { 77 return web.Text.InternalError(err) 78 } 79 return web.Text.Result("Logged Out") 80 }, web.SessionRequired) 81 82 app.GET("/", func(r *web.Ctx) web.Result { 83 return web.Text.Result("Yep") 84 }, web.SessionRequired) 85 86 if err := graceful.Shutdown(app); err != nil { 87 logger.FatalExit(err) 88 } 89 }