[refactor] login as separated page

This commit is contained in:
les 2020-01-03 22:24:27 +01:00
parent de0f9a9c4e
commit 0a0b609375
6 changed files with 100 additions and 134 deletions

83
pages/Login.vue Normal file
View file

@ -0,0 +1,83 @@
<template lang='pug'>
el-main
el-card.mt-5
h3(slot='header') Login
p(v-html="$t('login.description')")
div(v-loading='loading')
el-input.mb-2(v-model='email' type='email' name='email' prefix-icon='el-icon-user'
:placeholder='$t("common.email")' autocomplete='email' ref='email')
el-input.mb-1(v-model='password' @keyup.enter.native="submit"
prefix-icon='el-icon-lock' name='password'
type='password' :placeholder='$t("common.password")')
div
el-button.text-right(type='text' @click='forgot') {{$t('login.forgot_password')}}
el-button.mt-5(plain type="success"
:disabled='disabled' @click='submit') {{$t('common.login')}}
el-button(type='primary' plain href='/?ref=register' v-if='settings.allow_registration') {{$t('login.not_registered')}}
</template>
<script>
import { mapActions, mapState } from 'vuex'
import { Message } from 'element-ui'
import get from 'lodash/get'
export default {
name: 'Login',
data () {
return {
password: '',
email: '',
loading: false
}
},
head () {
title: 'Login'
},
computed: {
...mapState(['settings']),
disabled () {
return !this.email || !this.password
}
},
methods: {
...mapActions(['login']),
close () {
this.$router.replace('/')
},
async forgot () {
if (!this.email) {
Message({ message: this.$t('login.insert_email'), showClose: true, type: 'error' })
this.$refs.email.focus()
return
}
this.loading = true
await this.$axios.$post('/user/recover', { email: this.email })
this.loading = false
Message({ message: this.$t('login.check_email'), type: 'success' })
},
async submit (e) {
if (this.disabled) { return false }
e.preventDefault()
try {
this.loading = true
await this.$auth.loginWith('local', { data: { email: this.email, password: this.password } })
const user = await this.$axios.$get('/auth/user')
this.$auth.setUser(user)
this.loading = false
Message({ message: this.$t('login.ok'), showClose: true, type: 'success' })
this.close()
} catch (e) {
e = get(e, 'response.data.message', e)
Message({ message: this.$t('login.error') + this.$t(e), showClose: true, type: 'error' })
this.loading = false
return
}
this.email = this.password = ''
}
}
}
</script>

View file

@ -1,6 +1,5 @@
const express = require('express')
const multer = require('multer')
const bodyParser = require('body-parser')
const cors = require('cors')()
const { isAuth, isAdmin } = require('./auth')

View file

@ -1,7 +1,6 @@
const express = require('express')
const OAuthServer = require('express-oauth-server')
const oauth = express.Router()
const bodyParser = require('body-parser')
const oauthController = require('./controller/oauth')
const oauthServer = new OAuthServer({
@ -12,61 +11,30 @@ const oauthServer = new OAuthServer({
})
oauth.oauth = oauthServer
oauth.use(bodyParser.json())
oauth.use(bodyParser.urlencoded({ extended: false }))
oauth.use(express.urlencoded({ extended: false }))
oauth.use(express.json())
// post token
// oauth.post(oauthServer.authorize())
oauth.post('/token', (req, res, next) => {
return oauthServer.token()(req, res, next)
.then(code => {
console.error('dopo il token', code)
})
.catch(e => console.error('nel catch ', e))
})
oauth.post('/token', oauthServer.token())
/**
* create a new application
*/
oauth.get('/authorize', async (req, res, next) => {
if (!req.user) {
return res.redirect(`/?ref=login&redirect=${req.path}&client_id=${req.query.client_id}&redirect_uri=${req.query.redirect_uri}`)
return res.redirect(`/login?redirect=${req.path}&client_id=${req.query.client_id}&redirect_uri=${req.query.redirect_uri}`)
}
return oauthServer.authorize()(req, res, next).then(code => {
console.error('dentro authorize?', code)
console.error(req.locals)
return
// return res.redirect(`/?ref=authorize&client_id=${req.query.client_id}&redirect_uri=${req.query.redirect_uri}&code=${code}`)
}).catch(e => { console.error('porcodio catch ', e) })
return oauthServer.authorize()
})
oauth.post('/authorize', (req, res, next) => {
if (!req.user) {
return res.redirect(`/?ref=login&redirect=${req.path}&client_id=${req.query.client_id}&redirect_uri=${req.query.redirect_uri}`)
return res.redirect(`/login?redirect=${req.path}&client_id=${req.query.client_id}&redirect_uri=${req.query.redirect_uri}`)
}
console.error('sono nel post di authorize!')
const ret = oauthServer.authorize()
console.error('PORCODIO ', ret)
return ret(req, res, next).then(code => {
console.error('DAJE CHE ARRIVO QUI ', code)
console.error(req.locals)
next()
}).catch(e => console.error('CATCH ', e))
return oauthServer.authorize()
})
oauth.get('/login', (req, res) => {
res.render('login', {
client_id: req.query.client_id,
redirect_uri: req.query.redirect_uri,
redirect: req.query.redirect,
})
})
oauth.use((err, req, res, next) => {
res.status(400).json(err)
res.status(500).json(err)
})
// oauth.post('/login', )

View file

@ -40,6 +40,7 @@ module.exports = {
req.settings.user_locale = settingsController.user_locale[req.settings.locale]
moment.locale(req.settings.locale)
// TODO: oauth
// auth
jwt(req, res, async () => {
if (!req.user) { return next() }

View file

@ -1,84 +0,0 @@
const crypto = require('crypto')
const { promisify } = require('util')
const randomBytes = promisify(crypto.randomBytes)
async function randomString(len = 16) {
const bytes = await randomBytes(len*8)
return crypto
.createHash('sha1')
.update(bytes)
.digest('hex')
}
const OAuth = {
clients: [
{ clientId : 'confidentialApplication', clientSecret : 'topSecret',
redirectUris : ['https://localhost:13120/asdf', 'https://example-app.com/callback', 'https://oauthdebugger.com/debug'],
grants: ['password', 'authorization_code', 'client_credentials']
},
{
clientId: '1766891b7fb5fda4235dc7f0dde70fcd783371c2', clientSecret: 'ed6fdc050a415f178f2ac8428b76734edef75e5c',
grants: ['authorization_code'], redirectUris: ['urn:ietf:wg:oauth:2.0:oob'], scopes: ['write'], state: 'a'
}
],
tokens: [],
users: [{ id : '123', username: 'thomseddon', password: 'nightworld' }],
getAccessToken (bearerToken) {
console.error('dentro get access token', bearerToken, OAuth.tokens)
const tokens = OAuth.tokens.filter(token => token.accessToken === bearerToken)
return tokens.length ? tokens[0] : false
},
verifyScope (accessToken, scope) {
console.error('dentro verify scope', scope)
},
getRefreshToken (bearerToken) {
console.error('dentro refresh token')
const tokens = OAuth.tokens.filter( token => token.refreshToken === bearerToken )
return tokens.length ? tokens[0] : false
},
getClientCredentials () {
console.error('dentro get client credentials')
},
getClient (clientId, clientSecret) {
console.error(`getClient ${clientId} / ${clientSecret}`)
const clients = OAuth.clients.filter( client => client.clientId === clientId)
console.error(clients)
return clients.length ? clients[0] : false
},
getAuthorizationCode(authorizationCode) {
console.error('get auth code')
},
revokeAuthorizationCode (code) {
console.error('dentro revoke auth code ', code)
},
async createClient (client) {
client.client_id = await randomString(256)
client.client_secret = await randomString(256)
OAuth.clients.push(client)
return client
},
saveAuthorizationCode(code, client, user) {
console.error('dentro save auth code')
const ret = {
...code,
user,
client
}
OAuth.tokens.push(ret)
console.error('DIOCANEEEE salvo auth code!', OAuth.tokens)
return ret
},
saveToken (token) {
console.error('dentro save token')
},
// saveAuthorizationCode (token, client, user) {
// console.error('dentro save auth code')
// return true
// },
getUser (username, password) {
console.error('dentro get user')
}
}
module.exports = OAuth

View file

@ -26,29 +26,28 @@ app.use('/favicon.ico', express.static(path.resolve(config.favicon || './assets/
app.use('/logo.png', express.static('./static/gancio.png'))
app.use('/media/', express.static(config.upload_path))
// get instance settings
// initialize instance settings / authentication / locale
app.use(cookieParser())
app.use(helpers.initMiddleware)
app.use('/oauth', oauth)
// rss/ics/atom feed
app.get('/feed/:type', cors(), exportController.export)
// api!
app.use('/api', api)
app.use('/oauth', oauth)
// federation api / activitypub / webfinger / nodeinfo
app.use('/.well-known', webfinger)
app.use('/federation', federation)
// // Handle 500
// app.use((error, req, res, next) => {
// debug('Error 500: %s', error)
// res.status(500).send('500: Internal Server Error')
// })
app.use((error, req, res, next) => {
debug('Error 500: %s', error)
res.status(500).send('500: Internal Server Error')
})
// remaining request goes to nuxt
// first nuxt component is ./pages/index.vue
// first nuxt component is ./pages/index.vue (with ./layouts/default.vue)
module.exports = app