# 메서드

다음은 Wepin iOS Login Library에서 제공하는 메서드입니다.&#x20;

Wepin Login Library를 초기화한 후에 사용할 수 있습니다.

## loginWithOauthProvider

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

In-app browser가 열리고 OAuth provider에 로그인 합니다. Firebase 로그인 정보를 가져오려면 loginWithIdToken() 또는 loginWithAccessToken() 메서드를 호출해야 합니다.

**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)
```

이메일과 비밀번호로 Wepin Firebase에 회원가입을 합니다. 가입되지 않은 사용자의 경우 검증 이메일이 전송되며, `requiredEmailVerified` 오류가 발생합니다. 이미 가입된 사용자의 경우, `existedEmail` 오류가 발생하며 [loginWithEmailAndPassword](/widget-integration/ios-swift-sdk/login-library/methods.md#loginwithemailandpassword)를 호출하여 로그인 프로세스를 진행합니다. 로그인에 성공하면 Firebase 로그인 정보를 반환합니다.

**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)
```

이메일과 비밀번호를 사용하여 Wepin Firebase에 로그인합니다. 로그인에 성공하면 Firebase 로그인 정보를 반환합니다.

**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)
```

외부 ID 토큰을 사용하여 Wepin Firebase에 로그인합니다. 로그인에 성공하면 Firebase 로그인 정보를 반환합니다.

**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

WepinLogin 버전 1.0.0부터는 `sign` 값이 선택 사항입니다.

[Wepin Workspace](https://workspace.wepin.io/) 에서 발급된 인증 키를 제거하는 경우, `sign` 값을 사용하지 않아도 됩니다.

(Wepin Workspace > 개발 도구 메뉴 > 로그인 탭 > 인증 키 > 삭제)

> 인증 키 메뉴는 이전에 인증 키를 발급한 경우에만 표시됩니다.

WepinLogin 버전 1.1.0부터는 `sign` 값이 제거되었습니다.

WepinLogin 버전 1.1.0 을 사용하는 경우 반드시 [Wepin Workspace](https://workspace.wepin.io/) 에서 발급된 인증 키를 제거해야 합니다.
{% 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)
```

외부 Access Token을 사용하여 Wepin Firebase에 로그인합니다. 로그인에 성공하면 Firebase 로그인 정보를 반환합니다.

**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

WepinLogin 버전 1.0.0부터는 `sign` 값이 선택 사항입니다.

[Wepin Workspace](https://workspace.wepin.io/) 에서 발급된 인증 키를 제거하는 경우, `sign` 값을 사용하지 않아도 됩니다.

(Wepin Workspace > 개발 도구 메뉴 > 로그인 탭 > 인증 키 > 삭제)

> 인증 키 메뉴는 이전에 인증 키를 발급한 경우에만 표시됩니다.

WepinLogin 버전 1.1.0부터는 `sign` 값이 제거되었습니다.

WepinLogin 버전 1.1.0 을 사용하는 경우 반드시 [Wepin Workspace](https://workspace.wepin.io/) 에서 발급된 인증 키를 제거해야 합니다.
{% 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()
```

현재  Wepin Firebase 토큰의 정보를 가져옵니다.

**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)
```

지정한 로그인 프로바이더와 토큰을 사용하여 사용자를 위핀에 로그인합니다.

**Parameters**

매개변수는 이 모듈 내에서 loginWithEmailAndPassword(), loginWithIdToken(), loginWithAccessToken() 메서드의 반환 값을 활용해야 합니다.

* \<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()
```

위핀에 현재 로그인한 사용자의 정보를 가져옵니다.

**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()
```

위핀에 로그인한 사용자를 로그아웃합니다.

**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`은 더 이상 지원되지 않습니다\
• v1.1.0부터 `getSignForLogin()` 함수는 로그인 프로세스에서 `sign` 파라미터가 제거됨에 따라 더 이상 지원되지 않습니다.\
• 서명 없이 로그인하려면, **Wepin Workspace > 개발 도구 메뉴 > 로그인 탭 > 인증 키 > 삭제**에서 인증키를 삭제해 주세요.\
• 인증키 메뉴는 이전에 키를 생성한 경우에만 표시됩니다.
{% endhint %}

발급자를 확인하기 위한 서명을 생성합니다. 주로 ID Token 및 Access Token과 같은 로그인 관련 정보를 위한 서명을 생성하는 데 사용됩니다.

```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.

**Returns**

* String - The generated signature.

{% hint style="warning" %}
인증 키(privKey)는 안전하게 저장되어야 하며 외부에 노출되어서는 안 됩니다. 보안과 민감한 정보 보호를 강화하기 위해 getSignForLogin() 메서드는 프론트엔드가 아닌 백엔드에서 실행하는 것이 권장됩니다.
{% endhint %}

**Example**

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

## finalize

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

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/widget-integration/ios-swift-sdk/login-library/methods.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.
