github.com/clerkinc/clerk-sdk-go@v1.49.1/clerk/verification.go (about) 1 package clerk 2 3 import ( 4 "errors" 5 "net/http" 6 ) 7 8 const ( 9 CookieSession = "__session" 10 QueryParamSessionId = "_clerk_session_id" 11 ) 12 13 type VerificationService service 14 15 type verifyRequest struct { 16 Token string `json:"token"` 17 } 18 19 type Verification struct { 20 Status string `json:"status"` 21 Strategy string `json:"strategy"` 22 Attempts *int `json:"attempts"` 23 ExpireAt *int64 `json:"expire_at"` 24 VerifiedAtClient string `json:"verified_at_client,omitempty"` 25 26 // needed for Web3 27 Nonce *string `json:"nonce,omitempty"` 28 29 // needed for OAuth 30 ExternalVerificationRedirectURL *string `json:"external_verification_redirect_url,omitempty"` 31 Error []byte `json:"error,omitempty"` 32 } 33 34 func (s *VerificationService) Verify(req *http.Request) (*Session, error) { 35 if req == nil { 36 return nil, errors.New("cannot verify empty request") 37 } 38 cookie, err := req.Cookie(CookieSession) 39 if err != nil { 40 return nil, errors.New("couldn't find cookie " + CookieSession) 41 } 42 43 sessionToken := cookie.Value 44 sessionId := req.URL.Query().Get(QueryParamSessionId) 45 46 if sessionId == "" { 47 return s.useClientActiveSession(sessionToken) 48 } 49 50 return s.client.Sessions().Verify(sessionId, sessionToken) 51 } 52 53 func (s *VerificationService) useClientActiveSession(token string) (*Session, error) { 54 clientResponse, err := s.client.Clients().Verify(token) 55 if err != nil { 56 return nil, err 57 } 58 59 if clientResponse.LastActiveSessionID == nil { 60 return nil, errors.New("no active sessions for given client") 61 } 62 63 for _, session := range clientResponse.Sessions { 64 if session.ID == *clientResponse.LastActiveSessionID { 65 return session, nil 66 } 67 } 68 69 return nil, errors.New("active session not included in client's sessions") 70 } 71 72 func doVerify(client Client, url, token string, response interface{}) error { 73 tokenPayload := verifyRequest{Token: token} 74 req, _ := client.NewRequest("POST", url, &tokenPayload) 75 76 _, err := client.Do(req, response) 77 return err 78 }