| 1 |
package exampleop |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"net/http" |
| 7 |
|
| 8 |
"github.com/go-chi/chi/v5" |
| 9 |
"github.com/zitadel/oidc/v3/pkg/op" |
| 10 |
) |
| 11 |
|
| 12 |
type login struct { |
| 13 |
authenticate authenticate |
| 14 |
router chi.Router |
| 15 |
callback func(context.Context, string) string |
| 16 |
} |
| 17 |
|
| 18 |
func NewLogin(authenticate authenticate, callback func(context.Context, string) string, issuerInterceptor *op.IssuerInterceptor) *login { |
| 19 |
l := &login{ |
| 20 |
authenticate: authenticate, |
| 21 |
callback: callback, |
| 22 |
} |
| 23 |
l.createRouter(issuerInterceptor) |
| 24 |
return l |
| 25 |
} |
| 26 |
|
| 27 |
func (l *login) createRouter(issuerInterceptor *op.IssuerInterceptor) { |
| 28 |
l.router = chi.NewRouter() |
| 29 |
l.router.Get("/username", l.loginHandler) |
| 30 |
l.router.Post("/username", issuerInterceptor.HandlerFunc(l.checkLoginHandler)) |
| 31 |
} |
| 32 |
|
| 33 |
type authenticate interface { |
| 34 |
CheckUsernamePassword(username, password, id string) error |
| 35 |
} |
| 36 |
|
| 37 |
func (l *login) loginHandler(w http.ResponseWriter, r *http.Request) { |
| 38 |
err := r.ParseForm() |
| 39 |
if err != nil { |
| 40 |
http.Error(w, fmt.Sprintf("cannot parse form:%s", err), http.StatusInternalServerError) |
| 41 |
return |
| 42 |
} |
| 43 |
// the oidc package will pass the id of the auth request as query parameter |
| 44 |
// we will use this id through the login process and therefore pass it to the login page |
| 45 |
renderLogin(w, r.FormValue(queryAuthRequestID), nil) |
| 46 |
} |
| 47 |
|
| 48 |
func renderLogin(w http.ResponseWriter, id string, err error) { |
| 49 |
data := &struct { |
| 50 |
ID string |
| 51 |
Error string |
| 52 |
}{ |
| 53 |
ID: id, |
| 54 |
Error: errMsg(err), |
| 55 |
} |
| 56 |
err = templates.ExecuteTemplate(w, "login", data) |
| 57 |
if err != nil { |
| 58 |
http.Error(w, err.Error(), http.StatusInternalServerError) |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
func (l *login) checkLoginHandler(w http.ResponseWriter, r *http.Request) { |
| 63 |
err := r.ParseForm() |
| 64 |
if err != nil { |
| 65 |
http.Error(w, fmt.Sprintf("cannot parse form:%s", err), http.StatusInternalServerError) |
| 66 |
return |
| 67 |
} |
| 68 |
username := r.FormValue("username") |
| 69 |
password := r.FormValue("password") |
| 70 |
id := r.FormValue("id") |
| 71 |
err = l.authenticate.CheckUsernamePassword(username, password, id) |
| 72 |
if err != nil { |
| 73 |
renderLogin(w, id, err) |
| 74 |
return |
| 75 |
} |
| 76 |
http.Redirect(w, r, l.callback(r.Context(), id), http.StatusFound) |
| 77 |
} |