# Methods

These are the methods provided by the Wepin iOS Login Library.

Methods can be used after initialization of Wepin Login Library.

## loginWithOauthProvider

```swift
await wepin!.loginWithOauthProvider(params)
```

An in-app browser will open and proceed to log in to the OAuth provider. To retrieve Firebase login information, you need to execute either the loginWithIdToken() or loginWithAccessToken() method.

**Parameters**

* `params` \<WepinLoginOauth2Params>
  * `provider` <'google'|'naver'|'discord'|'apple'> - Provider for login
  * `clientId` \<String>
* `viewController` \<UIViewController>

**Returns**

* \<WepinLoginOauthResult>
  * `provider` \<String> - login provider
  * `token` \<String> - accessToken (if provider is "naver" or "discord") or idToken (if provider is "google" or "apple")
  * `type` \<WepinOauthTokenType> - type of token

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let oauthParams = WepinLoginOauth2Params(provider: "discord", clientId: self.discordClientId)
        let res = try await wepin!.loginWithOauthProvider(params: oauthParams, viewController: self)
        let privateKey = "private key for wepin id/access Token"
        // token sign 
        let sign = wepin!.getSignForLogin(privateKey: privateKey, message: res.token)
        //call loginWithIdToken() or loginWithAccessToken()
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## signUpWithEmailAndPassword

```swift
await wepin!.signUpWithEmailAndPassword(params: params)
```

Sign up for Wepin Firebase with an email and password. For users who have not yet registered, a verification email will be sent, and a `requiredEmailVerified` error will occur if verification is required. If the user is already registered, an `existedEmail` error will occur, and you should proceed with the login process by calling [loginWithEmailAndPassword](#loginwithemailandpassword). Upon successful login, Firebase login information is returned.

**Parameters**

* `params` \<WepinLoginWithEmailParams>
  * `email` \<String> - User email
  * `password` \<String> - User password
  * `locale` \<String> - **optional** Language for the verification email (default value: "en")

**Returns**

* \<WepinLoginResult>
  * `provider` \<WepinLoginProviders>
  * `token` \<WepinFBToken>
    * `idToken` \<String> - wepin firebase idToken
    * `refreshToken` - wepin firebase refreshToken

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let email = "EMAIL-ADDRESS"
        let password = "PASSWORD"
        let params = WepinLoginWithEmailParams(email: email, password: password)
        wepinLoginRes = try await wepin!.signUpWithEmailAndPassword(params: params)
        self.tvResult.text = String("Successed: \(wepinLoginRes)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## loginWithEmailAndPassword

```swift
await wepin!.loginWithEmailAndPassword(params: params)
```

This function logs in to the Wepin Firebase using your email and password. It returns Firebase login information upon successful login.

**Parameters**

* `params` \<WepinLoginWithEmailParams>
  * `email` \<String> - User email
  * `password` \<String> - User password

**Returns**

* \<WepinLoginResult>
  * `provider` \<WepinLoginProviders>
  * `token` \<WepinFBToken>
    * `idToken` \<String> - wepin firebase idToken
    * `refreshToken` \` - wepin firebase refreshToken

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let email = "EMAIL-ADDRESS"
        let password = "PASSWORD"
        let params = WepinLoginWithEmailParams(email: email, password: password)
        wepinLoginRes = try await wepin!.loginWithEmailAndPassword(params: params)
        self.tvResult.text = String("Successed: \(wepinLoginRes)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## loginWithIdToken

```swift
await wepin!.loginWithIdToken(params: params)
```

This function logs in to the Wepin Firebase using an external ID token. It returns Firebase login information upon successful login.

**Parameters**

* `params` \<WepinLoginOauthIdTokenRequest>
  * `idToken` \<String> - ID token value to be used for login
  * `sign` \<String> **optional** - Signature value for the token provided as the first parameter.(Returned value of [getSignForLogin()](#getsignforlogin))

{% hint style="warning" %}
&#x20;Note

Starting from WepinLogin version 1.0.0, the sign value is optional.

If you choose to remove the authentication key issued from the [Wepin Workspace](https://workspace.wepin.io/), you may opt not to use the `sign` value.

(Wepin Workspace > Development Tools menu > Login tab > Auth Key > Delete)

> The Auth Key menu is visible only if an authentication key was previously generated.

Starting from WepinLogin version 1.1.0, the sign is removed.

If you are using **WepinLogin version 1.1.0**, you **must delete the authentication key issued from Wepin Workspace**.
{% endhint %}

**Returns**

* \<WepinLoginResult>
  * `provider` \<WepinLoginProviders>
  * `token` \<WepinFBToken>
    * `idToken` \<String> - wepin firebase idToken
    * `refreshToken` \` - wepin firebase refreshToken

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let token = "ID-TOKEN"
        let sign = wepin!.getSignForLogin(privateKey: privateKey, message: token)
        let params = WepinLoginOauthIdTokenRequest(idToken: token, sign: sign!)
        wepinLoginRes = try await wepin!.loginWithIdToken(params: params)
        
        self.tvResult.text = String("Successed: \(wepinLoginRes)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## loginWithAccessToken

```swift
await wepin!.loginWithAccessToken(params: params)
```

This function logs in to the Wepin Firebase using an external access token. It returns Firebase login information upon successful login.

**Parameters**

* `params` \<WepinLoginOauthAccessTokenRequest>
  * `provider` <"naver"|"discord"> - Provider that issued the access token
  * `accessToken` \<String> - Access token value to be used for login
  * `sign` \<String> **optional** - Signature value for the token provided as the first parameter. (Returned value of [getSignForLogin()](#getsignforlogin))

{% hint style="warning" %}
&#x20;Note

Starting from WepinLogin version 1.0.0, the sign value is optional.

If you choose to remove the authentication key issued from the [Wepin Workspace](https://workspace.wepin.io/), you may opt not to use the `sign` value.

(Wepin Workspace > Development Tools menu > Login tab > Auth Key > Delete)

> The Auth Key menu is visible only if an authentication key was previously generated.

Starting from WepinLogin version 1.1.0, the sign is removed.

If you are using **WepinLogin version 1.1.0**, you **must delete the authentication key issued from Wepin Workspace**.
{% endhint %}

**Returns**

* \<WepinLoginResult>
  * `provider` \<WepinLoginProviders>
  * `token` \<WepinFBToken>
    * `idToken` \<String> - wepin firebase idToken
    * `refreshToken` \` - wepin firebase refreshToken

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let token = "ACCESS-TOKEN"
        let sign = wepin!.getSignForLogin(privateKey: privateKey, message: token)
        let params = WepinLoginOauthAccessTokenRequest(provider: "discord", accessToken: token, sign: sign!)
        wepinLoginRes = try await wepin!.loginWithAccessToken(params: params)
        self.tvResult.text = String("Successed: \(wepinLoginRes)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## getRefreshFirebaseToken

```swift
await wepin!.getRefreshFirebaseToken()
```

This method retrieves the current firebase token's information from the Wepin.

**Parameters**

* void

**Returns**

* \<WepinLoginResult>
  * `provider` \<WepinLoginProviders>
  * `token` \<WepinFBToken>
    * `idToken` \<String> - wepin firebase idToken
    * `refreshToken` \` - wepin firebase refreshToken

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let res = try await wepin!.getRefreshFirebaseToken()
        wepinLoginRes = res
        self.tvResult.text = String("Successed: \(res)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## loginWepin

```swift
await wepin!.loginWepin(params: wepinLoginRes)
```

This method logs the user into the Wepin application using the specified provider and token.

**Parameters**

The parameters should utilize the return values from the `loginWithEmailAndPassword()`, `loginWithIdToken()`, and `loginWithAccessToken()` methods within this module.

* \<WepinLoginResult>
  * `provider` \<WepinLoginProviders>
  * `token` \<WepinFBToken>
    * `idToken` \<String> - Wepin Firebase idToken
    * `refreshToken` \` - Wepin Firebase refreshToken

**Returns**

* \<WepinUser> - An object containing the user's login status and information. The object includes:
  * status <'success'|'fail'> - The login status.
  * userInfo \<WepinUserInfo> **optional** - The user's information, including:
    * userId \<String> - The user's ID.
    * email \<String> - The user's email.
    * provider \<WepinLoginProviders> - 'google'|'apple'|'naver'|'discord'|'email'|'external\_token'
    * use2FA \<Bool> - Whether the user uses two-factor authentication.
  * walletId \<String> **optional** - The user's wallet ID.
  * userStatus: \<WepinUserStatus> **optional** - The user's status of wepin login. including:
    * loginStatus: \<WepinLoginStatus> - 'complete' | 'pinRequired' | 'registerRequired' - If the user's loginStatus value is not complete, it must be registered in the wepin.
    * pinRequired: **optional**
  * token: \<WepinToken> **optional** - The user's token of wepin.
    * refresh: \<String>
    * access \<String>

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let res = try await wepin!.loginWepin(params: wepinLoginRes)
        wepinLoginRes = nil
        self.tvResult.text = String("Successed: \(res)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## getCurrentWepinUser

```swift
await wepin!.getCurrentWepinUser()
```

This method retrieves the current logged-in user's information from the Wepin.

**Parameters**

* void

**Returns**

* \<WepinUser> - An object containing the user's login status and information. The object includes:
  * status <'success'|'fail'> - The login status.
  * userInfo \<WepinUserInfo> **optional** - The user's information, including:
    * userId \<String> - The user's ID.
    * email \<String> - The user's email.
    * provider \<WepinLoginProviders> - 'google'|'apple'|'naver'|'discord'|'email'|'external\_token'
    * use2FA \<Bool> - Whether the user uses two-factor authentication.
  * walletId \<String> **optional** - The user's wallet ID.
  * userStatus: \<WepinUserStatus> **optional** - The user's status of wepin login. including:
    * loginStatus: \<WepinLoginStatus> - 'complete' | 'pinRequired' | 'registerRequired' - If the user's loginStatus value is not complete, it must be registered in the wepin.
    * pinRequired: **optional**
  * token: \<WepinToken> **optional** - The user's token of wepin.
    * refresh: \<String>
    * access \<String>

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let res = try await wepin!.getCurrentWepinUser()
        self.tvResult.text = String("Successed: \(res)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## logoutWepin

```swift
await wepin!.logoutWepin()
```

This method logs out the user logged into Wepin.

**Parameters**

* void

**Returns**

* \<Bool>

**Exception**

* [Wepin Login Error](#wepinloginerror)

**Example**

```swift
    do {
        let res = try await wepin!.logoutWepin()
        self.tvResult.text = String("Successed: \(res)")
    } catch (let error){
        self.tvResult.text = String("Faild: \(error)")
    }
```

## getSignForLogin(Deprecated)

{% hint style="danger" %}
🔄 `getSignForLogin` is no longer supported\
• Starting from **v1.1.0**, the `getSignForLogin()` function is no longer supported because the `sign` parameter has been removed from the login process.\
• To log in without a signature, please delete the authentication key from **Wepin Workspace > Development Tools menu > Login tab > Auth Key > Delete**\
• The "Auth Key" menu is only visible if a key has been previously generated.
{% endhint %}

Generates signatures to verify the issuer. It is mainly used to generate signatures for login-related information such as ID tokens and access tokens.

```swift
wepin!.getSignForLogin(privateKey: privateKey, message: "")
```

**Parameters**

* `privKey` \<String> - The authentication key used for signature generation.
* `message` \<String> - The message or payload to be signed.

{% hint style="info" %}
The key for signing can be obtained from [Wepin Workspace](https://workspace.wepin.io/). In the Development Tools menu, click **Get your authentication key** on the Login tab to retrieve the authentication key.
{% endhint %}

**Returns**

* String - The generated signature.

{% hint style="warning" %}
The authentication key (`privKey`) must be stored securely and must not be exposed to the outside. It is recommended to execute the `getSignForLogin()` method on the backend rather than the frontend for enhanced security and protection of sensitive information.
{% endhint %}

**Example**

```swift
let privKey = '0400112233445566778899001122334455667788990011223344556677889900'
let idToken = 'idtokenabcdef'
let sign = wepin!.getSignForLogin(privateKey: privKey, message: idToken)
```

## finalize

```swift
wepin!.finalize()
```

This method finalizes the Wepin Login Library.

**Parameters**

* void

**Returns**

* void

**Example**

```swift
wepin!.finalize()
```

## WepinLoginError

| Error                          | Error Description                                                                                                                                                                                    |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `invalidParameters`            | One or more parameters provided are invalid or missing.                                                                                                                                              |
| `notInitialized`               | The WepinLoginLibrary has not been properly initialized.                                                                                                                                             |
| `invalidAppKey`                | The Wepin app key is invalid.                                                                                                                                                                        |
| `invalidLoginProvider`         | The login provider specified is not supported or is invalid.                                                                                                                                         |
| `invalidToken`                 | The token does not exist.                                                                                                                                                                            |
| `invalidLoginSession`          | The login session information does not exist.                                                                                                                                                        |
| `userCancelled`                | The user has cancelled the operation.                                                                                                                                                                |
| `unkonwError(message: String)` | An unknown error has occurred, and the cause is not identified.                                                                                                                                      |
| `notConnectedInternet`         | The system is unable to detect an active internet connection.                                                                                                                                        |
| `failedLogin`                  | The login attempt has failed due to incorrect credentials or other issues.                                                                                                                           |
| `alreadyLogout`                | The user is already logged out, so the logout operation cannot be performed again.                                                                                                                   |
| `alreadyInitialized`           | The WepinLoginLibrary is already initialized, so the logout operation cannot be performed again.                                                                                                     |
| `invalidEmailDomain`           | The provided email address's domain is not allowed or recognized by the system.                                                                                                                      |
| `failedSendEmail`              | The system encountered an error while sending an email. This is because the email address is invalid or we sent verification emails too often. Please change your email or try again after 1 minute. |
| `requiredEmailVerified`        | Email verification is required to proceed with the requested operation.                                                                                                                              |
| `incorrectEmailForm`           | The provided email address does not match the expected format.                                                                                                                                       |
| `incorrectPasswordForm`        | The provided password does not meet the required format or criteria.                                                                                                                                 |
| `notInitializedNetwork`        | The network or connection required for the operation has not been properly initialized.                                                                                                              |
| `requiredSignupEmail`          | The user needs to sign up with an email address to proceed.                                                                                                                                          |
| `failedEmailVerified`          | The WepinLoginLibrary encountered an issue while attempting to verify the provided email address.                                                                                                    |
| `failedPasswordStateSetting`   | The WepinLoginLibrary failed to set state of the password.                                                                                                                                           |
| `failedPasswordSetting`        | The WepinLoginLibrary failed to set the password.                                                                                                                                                    |
| `existedEmail`                 | The provided email address is already registered in Wepin.                                                                                                                                           |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.wepin.io/en/widget-integration/ios-swift-sdk/login-library/method.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
