# Login

O processo de autenticação para o Social Service envolve interagir com o [servidor Matrix](https://matrix.org/), usado nos bastidores para o subsistema de chat privado. Os usuários devem entrar no Matrix usando seu endereço, assinando uma operação fetch para obter um token de autenticação. Esse token é então usado para autorizar interações com o Social Service.

### Requisição HTTP

Para adquirir o token de autenticação, como [a documentação do Matrix se refere](https://spec.matrix.org/v1.3/client-server-api/#login), uma requisição POST deve ser feita para a seguinte URL: `https://social.decentraland.org/_matrix/client/r0/login` como no exemplo abaixo.

Para fazer login no Matrix, você precisa criar e assinar uma mensagem com AuthChain.

#### Corpo da Requisição

```json
{
  "auth_chain": authChain,
  "identifier": {
    "type": "m.id.user",
    "user": address
  },
  "timestamp": timestamp.toString(),
  "type": "m.login.decentraland"
}
```

#### Corpo da Resposta

```json
{
  "user_id": "@0x123abC:decentraland.org",
  "social_user_id": "0x123abC",
  "access_token": "syt_SomETokEN",
  "device_id": "FRFREGRG",
  "home_server": "decentraland.org",
  "well_known": {
      "m.homeserver": {
          "base_url": "https://synapse.decentraland.org/"
      }
  }
}
```

O token de autenticação, presente no `access_token` campo, é necessário para interações subsequentes com o Social Service.

### Exemplo de Código JS

```javascript
import fetch from 'cross-fetch'
import { AuthIdentity, Authenticator } from '@dcl/crypto'

export async function getMatrixToken(matrixUrl: string, address: string, identity: AuthIdentity): Promise<string> {
  const timestamp = Date.now()
  const authChain = Authenticator.signPayload(identity, timestamp.toString())

  try {
    const response = await fetch(`${matrixUrl}/_matrix/client/r0/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        auth_chain: authChain,
        identifier: {
          type: 'm.id.user',
          user: address
        },
        timestamp: timestamp.toString(),
        type: 'm.login.decentraland'
      })
    })

    if (response.ok) {
      const responseBody = await response.json()
      return responseBody.access_token
    } else {
      throw new Error(`Matrix server responded with a ${response.status} status code`)
    }
  } catch (error) {
    throw new MatrixLoginError(isErrorWithMessage(error) ? error.message : 'Unknown error')
  }
}
```

Código de [social-rpc-client-js](https://github.com/decentraland/social-rpc-client-js/blob/main/src/client.ts#L14)
