1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| package main
import ( "context" "fmt" "github.com/redis/go-redis/v9" uuid "github.com/satori/go.uuid" "log" "net/http" "time" )
var rdb = redis.NewClient(&redis.Options{ Addr: "xxxxxxxxxx", Password: "xxxxxxxxxx", DB: 0, }) var ctx = context.Background()
func CrosMiddleware(handler http.HandlerFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS") if r.Method == "OPTIONS" { w.WriteHeader(200) return } handler.ServeHTTP(w, r) }) }
func auth(w http.ResponseWriter, r *http.Request) { if username := r.FormValue("username"); username == "admin" && r.FormValue("password") == "admin"{ tk := uuid.NewV4().String() cookie := &http.Cookie{ Name: "token", Value: tk, } if err := rdb.Set(ctx, "user.login.session."+username, tk, 0).Err();err != nil { log.Fatal("redis error") } http.SetCookie(w, cookie) ticket := uuid.NewV4().String() if err1 := rdb.Set(ctx, "user.login.ticket."+ticket, username, 100*time.Second).Err();err1 != nil { log.Fatal("redis error") } w.Write([]byte(fmt.Sprintf("{\"code\":200,\"msg\":\"success\",\"ticket\":\"%s\"}", ticket))) } else if cookie, cookieErr := r.Cookie("token"); cookieErr == nil { username := rdb.Get(ctx, "user.login.session."+cookie.Value).Val() ticket := uuid.NewV4().String() err1 := rdb.Set(ctx, "user.login.ticket."+ticket, username, 100*time.Second).Err() if err1 != nil { log.Fatal("redis error") } w.Write([]byte(fmt.Sprintf("{\"code\":200,\"msg\":\"success\",\"ticket\":\"%s\"}", ticket))) } else { w.Write([]byte("{\"code\":500,\"msg\":\"fail\",\"ticket\":\"null\"}")) } }
func ticketAuth(w http.ResponseWriter, r *http.Request) { ticket := r.FormValue("ticket") tk := uuid.NewV4().String() cookie := &http.Cookie{ Name: "token", Value: tk, } http.SetCookie(w, cookie) if err := rdb.Set(ctx, "user.login.session."+rdb.Get(ctx, "user.login.ticket."+ticket).Val(), tk, 0).Err();err != nil { log.Fatal("redis error") } }
func main() { http.Handle("/auth", CrosMiddleware(auth)) http.Handle("/sso", CrosMiddleware(ticketAuth)) err := http.ListenAndServe(":80", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
|