예제 #1
0
func authenticate(userSession *session.UserSession) error {
	// Try to authenticate with the stored access token
	err := theService.oauthService.Authenticate(userSession.AccessToken)
	if err == nil {
		// Access token valid, return
		return nil
	}
	// Access token might be expired, let's try refreshing...

	// Fetch the client
	client, err := theService.oauthService.FindClientByClientID(
		userSession.ClientID, // client ID
	)
	if err != nil {
		return err
	}

	// Validate the refresh token
	theRefreshToken, err := theService.oauthService.GetValidRefreshToken(
		userSession.RefreshToken, // refresh token
		client, // client
	)
	if err != nil {
		return err
	}

	// Create a new access token
	accessToken, err := theService.oauthService.GrantAccessToken(
		theRefreshToken.Client, // client
		theRefreshToken.User,   // user
		theRefreshToken.Scope,  // scope
	)
	if err != nil {
		return err
	}

	// Create or retrieve a refresh token
	refreshToken, err := theService.oauthService.GetOrCreateRefreshToken(
		theRefreshToken.Client, // client
		theRefreshToken.User,   // user
		theRefreshToken.Scope,  // scope
	)
	if err != nil {
		return err
	}

	userSession.AccessToken = accessToken.Token
	userSession.RefreshToken = refreshToken.Token

	return nil
}
예제 #2
0
func (m *loggedInMiddleware) authenticate(userSession *session.UserSession) error {
	// Try to authenticate with the stored access token
	_, err := m.service.GetOauthService().Authenticate(userSession.AccessToken)
	if err == nil {
		// Access token valid, return
		return nil
	}
	// Access token might be expired, let's try refreshing...

	// Fetch the client
	client, err := m.service.GetOauthService().FindClientByClientID(
		userSession.ClientID, // client ID
	)
	if err != nil {
		return err
	}

	// Validate the refresh token
	theRefreshToken, err := m.service.GetOauthService().GetValidRefreshToken(
		userSession.RefreshToken, // refresh token
		client, // client
	)
	if err != nil {
		return err
	}

	// Log in the user
	accessToken, refreshToken, err := m.service.GetOauthService().Login(
		theRefreshToken.Client,
		theRefreshToken.User,
		theRefreshToken.Scope,
	)
	if err != nil {
		return err
	}

	userSession.AccessToken = accessToken.Token
	userSession.RefreshToken = refreshToken.Token

	return nil
}