authCallbackHandler handles the OAuth2 PKCE callback to exchange the authorization code for a rill access token.
()
| 844 | |
| 845 | // authCallbackHandler handles the OAuth2 PKCE callback to exchange the authorization code for a rill access token. |
| 846 | func (s *Server) authCallbackHandler() http.Handler { |
| 847 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 848 | code := r.URL.Query().Get("code") |
| 849 | if code == "" { |
| 850 | http.Error(w, "missing code", http.StatusBadRequest) |
| 851 | return |
| 852 | } |
| 853 | state := r.URL.Query().Get("state") |
| 854 | if code == "" { |
| 855 | http.Error(w, "missing state", http.StatusBadRequest) |
| 856 | return |
| 857 | } |
| 858 | |
| 859 | authenticator, ok := s.app.pkceAuthenticators[state] |
| 860 | if !ok { |
| 861 | http.Error(w, "invalid state", http.StatusBadRequest) |
| 862 | return |
| 863 | } |
| 864 | |
| 865 | // remove authenticator from map |
| 866 | delete(s.app.pkceAuthenticators, state) |
| 867 | |
| 868 | if authenticator == nil { |
| 869 | http.Error(w, "failed to get authenticator", http.StatusInternalServerError) |
| 870 | return |
| 871 | } |
| 872 | |
| 873 | // Exchange the code for an access token |
| 874 | token, err := authenticator.ExchangeCodeForToken(code) |
| 875 | if err != nil { |
| 876 | http.Error(w, fmt.Sprintf("failed to exchange code for token: %s", err), http.StatusInternalServerError) |
| 877 | return |
| 878 | } |
| 879 | |
| 880 | // Save token and reload config |
| 881 | err = s.app.ch.DotRill.SetAccessToken(token) |
| 882 | if err != nil { |
| 883 | http.Error(w, fmt.Sprintf("failed to save access token: %s", err), http.StatusInternalServerError) |
| 884 | return |
| 885 | } |
| 886 | err = s.app.ch.ReloadAdminConfig() |
| 887 | if err != nil { |
| 888 | http.Error(w, fmt.Sprintf("failed to reload admin config: %s", err), http.StatusInternalServerError) |
| 889 | return |
| 890 | } |
| 891 | |
| 892 | // Redirect back to url provided by caller when initiating auth flow |
| 893 | http.Redirect(w, r, authenticator.OriginURL, http.StatusFound) |
| 894 | }) |
| 895 | } |
| 896 | |
| 897 | // logoutHandler logs out the user and unsets the token stored |
| 898 | func (s *Server) logoutHandler() http.Handler { |
no test coverage detected