aboutsummaryrefslogtreecommitdiff
path: root/src/components/login_form/login_form.js
blob: 0b574a048bd70039bb7840966e5a97f29ea7c269 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
import oauthApi from '../../services/new_api/oauth.js'

const LoginForm = {
  data: () => ({
    user: {},
    error: false
  }),
  computed: {
    isPasswordAuth () { return this.requiredPassword },
    isTokenAuth () { return this.requiredToken },
    ...mapState({
      registrationOpen: state => state.instance.registrationOpen,
      instance: state => state.instance,
      loggingIn: state => state.users.loggingIn,
      oauth: state => state.oauth
    }),
    ...mapGetters(
      'authFlow', ['requiredPassword', 'requiredToken', 'requiredMFA']
    )
  },
  methods: {
    ...mapMutations('authFlow', ['requireMFA']),
    ...mapActions({ login: 'authFlow/login' }),
    submit () {
      this.isTokenAuth ? this.submitToken() : this.submitPassword()
    },
    submitToken () {
      const { clientId, clientSecret } = this.oauth
      const data = {
        clientId,
        clientSecret,
        instance: this.instance.server,
        commit: this.$store.commit
      }

      oauthApi.getOrCreateApp(data)
        .then((app) => { oauthApi.login({ ...app, ...data }) })
    },
    submitPassword () {
      const { clientId } = this.oauth
      const data = {
        clientId,
        oauth: this.oauth,
        instance: this.instance.server,
        commit: this.$store.commit
      }
      this.error = false

      oauthApi.getOrCreateApp(data).then((app) => {
        oauthApi.getTokenWithCredentials(
          {
            ...app,
            instance: data.instance,
            username: this.user.username,
            password: this.user.password
          }
        ).then((result) => {
          if (result.error) {
            if (result.error === 'mfa_required') {
              this.requireMFA({ app: app, settings: result })
            } else if (result.identifier === 'password_reset_required') {
              this.$router.push({ name: 'password-reset', params: { passwordResetRequested: true } })
            } else {
              this.error = result.error
              this.focusOnPasswordInput()
            }
            return
          }
          this.login(result).then(() => {
            this.$router.push({ name: 'friends' })
          })
        })
      })
    },
    clearError () { this.error = false },
    focusOnPasswordInput () {
      let passwordInput = this.$refs.passwordInput
      passwordInput.focus()
      passwordInput.setSelectionRange(0, passwordInput.value.length)
    }
  }
}

export default LoginForm