Skip to content

Commit

Permalink
fixed authentication via cookies, oauth login,
Browse files Browse the repository at this point in the history
  • Loading branch information
hunterlong committed May 4, 2020
1 parent 2aa3bee commit 42e1b02
Show file tree
Hide file tree
Showing 19 changed files with 180 additions and 95 deletions.
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"vue-apexcharts": "^1.5.2",
"vue-clipboard2": "^0.3.1",
"vue-codemirror": "^4.0.6",
"vue-cookies": "^1.7.0",
"vue-flatpickr-component": "^8.1.5",
"vue-github-button": "^1.1.2",
"vue-moment": "^4.1.0",
Expand Down
30 changes: 13 additions & 17 deletions frontend/src/API.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as Sentry from "@sentry/browser";
import * as Integrations from "@sentry/integrations";
const qs = require('querystring');

const tokenKey = "statping_user";
const tokenKey = "statping_auth";
const errorReporter = "https://[email protected]/3"

class Api {
Expand All @@ -29,6 +29,10 @@ class Api {
return axios.post('api/core', obj).then(response => (response.data))
}

async oauth_save(obj) {
return axios.post('api/oauth', obj).then(response => (response.data))
}

async setup_save(data) {
return axios.post('api/setup', qs.stringify(data)).then(response => (response.data))
}
Expand Down Expand Up @@ -228,19 +232,11 @@ class Api {

async login(username, password) {
const f = {username: username, password: password}
return axios.post('api/login', qs.stringify(f))
.then(response => (response.data))
return axios.post('api/login', qs.stringify(f)).then(response => (response.data))
}

async logout() {
await axios.get('api/logout').then(response => (response.data))
return localStorage.removeItem(tokenKey)
}

saveToken(username, token, admin) {
const user = {username: username, token: token, admin: admin}
localStorage.setItem(tokenKey, JSON.stringify(user));
return user
return axios.get('api/logout').then(response => (response.data))
}

async scss_base() {
Expand All @@ -255,17 +251,17 @@ class Api {
}

token() {
const tk = localStorage.getItem(tokenKey)
const tk = $cookies.get(tokenKey)
if (!tk) {
return {};
return {admin: false};
}
return JSON.parse(tk);
return tk;
}

authToken() {
let user = JSON.parse(localStorage.getItem(tokenKey));
if (user && user.token) {
return {'Authorization': 'Bearer ' + user.token};
const tk = $cookies.get(tokenKey)
if (tk.token) {
return {'Authorization': 'Bearer ' + tk.token};
} else {
return {};
}
Expand Down
9 changes: 3 additions & 6 deletions frontend/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,19 @@
this.$router.push('/setup')
}
if (this.$route.path !== '/setup') {
if (this.core.logged_in) {
if (this.$store.state.admin) {
await this.$store.dispatch('loadAdmin')
} else {
await this.$store.dispatch('loadRequired')
}
this.loaded = true
}
},
async mounted() {
if (this.$route.path !== '/setup') {
const tk = localStorage.getItem("statping_user")
if (this.core.logged_in) {
if (this.$store.state.admin) {
this.logged_in = true
await this.$store.dispatch('loadAdmin')
// await this.$store.dispatch('loadAdmin')
}
}
}
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/components/Dashboard/TopNav.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
</li>
</ul>
<span class="navbar-text">
<a href="#" class="nav-link" v-on:click="logout">Logout</a>
<a href="#" class="nav-link" @click.prevent="logout">Logout</a>
</span>
</div>
</nav>
Expand All @@ -37,6 +37,7 @@

<script>
import Api from "../../API"
import Vue from "vue";
export default {
name: 'TopNav',
Expand All @@ -51,6 +52,7 @@
this.$store.commit('setHasAllData', false)
this.$store.commit('setToken', null)
this.$store.commit('setAdmin', false)
this.$cookies.remove("statping_auth")
await this.$router.push('/logout')
}
}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Index/Footer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<a href="https://github.com/statping/statping" target="_blank">
Statping {{core.version}} made with <font-awesome-icon icon="heart"/>
</a> |
<router-link :to="core.logged_in ? '/dashboard' : '/login'">Dashboard</router-link>
<router-link :to="$store.state.admin ? '/dashboard' : '/login'">Dashboard</router-link>
</div>
<div v-else class="footer text-center mb-4 p-2" v-html="core.footer"></div>
</footer>
Expand Down
21 changes: 11 additions & 10 deletions frontend/src/forms/Login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,16 @@
</div>
</form>

<a v-if="oauth.gh_client_id" :href="GHlogin()" class="btn btn-block">
Github Login
<a v-if="oauth.gh_client_id" @click.prevent="GHlogin" href="#" class="btn btn-block btn-outline-dark">
<font-awesome-icon :icon="['fab', 'github']" /> Login with Github
</a>

<a v-if="oauth.slack_client_id" :href="Slacklogin()" class="btn btn-block">
Slack Login
<a v-if="oauth.slack_client_id" @click.prevent="Slacklogin" href="#" class="btn btn-block btn-outline-dark">
<font-awesome-icon :icon="['fab', 'slack']" /> Login with Slack
</a>

<a v-if="oauth.google_client_id" :href="Googlelogin()" class="btn btn-block">
Google Login
<a v-if="oauth.google_client_id" @click.prevent="Googlelogin" href="#" class="btn btn-block btn-outline-dark">
<font-awesome-icon :icon="['fab', 'google']" /> Login with Google
</a>

</div>
Expand Down Expand Up @@ -80,21 +80,22 @@
if (auth.error) {
this.error = true
} else if (auth.token) {
this.auth = Api.saveToken(this.username, auth.token, auth.admin)
const u = {username: this.username, admin: auth.admin, token: auth.token}
this.$cookies.set("statping_auth", JSON.stringify(u))
this.$store.dispatch('loadAdmin')
this.$store.commit('setAdmin', auth.admin)
this.$router.push('/dashboard')
}
this.loading = false
},
GHlogin() {
return `https://github.com/login/oauth/authorize?client_id=${this.oauth.gh_client_id}&redirect_uri=${this.core.domain}/api/oauth/github&scope=user,repo`
window.location = `https://github.com/login/oauth/authorize?client_id=${this.oauth.gh_client_id}&redirect_uri=${this.core.domain}/oauth/github&scope=user,repo`
},
Slacklogin() {
return `https://slack.com/oauth/authorize?client_id=${this.oauth.slack_client_id}&redirect_uri=${this.core.domain}/api/oauth/slack&scope=users.profile:read,users:read.email`
window.location = `https://slack.com/oauth/authorize?client_id=${this.oauth.slack_client_id}&redirect_uri=${this.core.domain}/oauth/slack&scope=identity.basic`
},
Googlelogin() {
return `https://accounts.google.com/signin/oauth?client_id=${this.oauth.google_client_id}&redirect_uri=${this.core.domain}/api/oauth/google&response_type=code&scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email`
window.location = `https://accounts.google.com/signin/oauth?client_id=${this.oauth.google_client_id}&redirect_uri=${this.core.domain}/oauth/google&response_type=code&scope=https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email`
}
}
}
Expand Down
23 changes: 17 additions & 6 deletions frontend/src/forms/OAuth.vue
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@
core() {
return this.$store.getters.core
},
oauth() {
auth() {
return this.$store.getters.oauth
}
},
Expand All @@ -171,10 +171,22 @@
google_enabled: false,
slack_enabled: false,
github_enabled: false,
local_enabled: false
local_enabled: false,
oauth: {
gh_client_id: "",
gh_client_secret: "",
google_client_id: "",
google_client_secret: "",
oauth_domains: "",
oauth_providers: "",
slack_client_id: "",
slack_client_secret: "",
slack_team: ""
}
}
},
mounted() {
this.oauth = this.auth
this.local_enabled = this.has('local')
this.github_enabled = this.has('github')
this.google_enabled = this.has('google')
Expand Down Expand Up @@ -207,10 +219,9 @@
let c = this.core
c.oauth = this.oauth
c.oauth.oauth_providers = this.providers()
await Api.core_save(c)
const core = await Api.core()
this.$store.commit('setCore', core)
this.$store.commit('setOAuth', c.oauth)
await Api.oauth_save(c)
const oauth = await Api.oauth()
this.$store.commit('setOAuth', oauth)
}
}
}
Expand Down
12 changes: 8 additions & 4 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,23 @@ import VueRouter from 'vue-router'
import VueApexCharts from 'vue-apexcharts'
import VueObserveVisibility from 'vue-observe-visibility'
import VueClipboard from 'vue-clipboard2'
import VueCookies from 'vue-cookies'

import App from '@/App.vue'
import store from './store'

import router from './routes'
import "./mixin"
import "./icons"

Vue.component('apexchart', VueApexCharts)

Vue.use(VueClipboard);
Vue.use(VueRouter);
Vue.use(VueObserveVisibility);
Vue.use(VueCookies);
Vue.$cookies.config('3d')

import router from './routes'
import "./mixin"
import "./icons"


Vue.config.productionTip = false
new Vue({
Expand Down
18 changes: 15 additions & 3 deletions frontend/src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,18 @@ const routes = [
meta: {
requiresAuth: true
},
beforeEnter: CheckAuth,
beforeEnter: async (to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
let tk = await Api.token()
if (to.path !== '/login' && !tk.admin) {
next('/login')
return
}
next()
} else {
next()
}
},
children: [{
path: '',
component: DashboardIndex,
Expand Down Expand Up @@ -135,9 +146,10 @@ const router = new VueRouter({
routes
})

function CheckAuth(to, from, next) {
let CheckAuth = (to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
let item = localStorage.getItem("statping_user")
let item = this.$cookies.get("statping_auth")
window.console.log(item)
if (to.path !== '/login' && !item) {
next('/login')
return
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ export default new Vuex.Store({
state.hasPublicData = bool
},
setCore (state, core) {
window.console.log('GETTING CORE')
state.core = core
},
setToken (state, token) {
Expand Down Expand Up @@ -146,10 +145,11 @@ export default new Vuex.Store({
},
async loadCore(context) {
const core = await Api.core()
const token = await Api.token()
context.commit("setCore", core);
context.commit('setAdmin', core.admin)
context.commit('setAdmin', token.admin)
context.commit('setCore', core)
context.commit('setUser', core.logged_in)
context.commit('setUser', token.token!==undefined)
},
async loadRequired(context) {
const groups = await Api.groups()
Expand Down
2 changes: 1 addition & 1 deletion frontend/vue.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ module.exports = {
},
'/oauth': {
logLevel: 'debug',
target: 'http://0.0.0.0:8585'
target: 'http://0.0.0.0:8585/oauth/'
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -11838,6 +11838,11 @@ vue-codemirror@^4.0.6:
codemirror "^5.41.0"
diff-match-patch "^1.0.0"

vue-cookies@^1.7.0:
version "1.7.0"
resolved "https://registry.yarnpkg.com/vue-cookies/-/vue-cookies-1.7.0.tgz#dd8f147ff1579e0cbd5f352dc5dff2696d8760b8"
integrity sha512-vuEUm6wYMMrFAHFCrkzIUAy8+MgPAbBGmYXnk2M6X6O2KHbMT1wuDD2izacmsSUp6ZM02e23MJRtPRobl88VMg==

vue-eslint-parser@^4.0.2:
version "4.0.3"
resolved "https://registry.yarnpkg.com/vue-eslint-parser/-/vue-eslint-parser-4.0.3.tgz#80cf162e484387b2640371ad21ba1f86e0c10a61"
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/gogo/protobuf v1.3.1 // indirect
github.com/golang/protobuf v1.3.5
github.com/gorilla/mux v1.7.4
github.com/gorilla/securecookie v1.1.1
github.com/gorilla/sessions v1.2.0
github.com/jinzhu/gorm v1.9.12
github.com/joho/godotenv v1.3.0
Expand Down
21 changes: 13 additions & 8 deletions handlers/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,7 @@ type apiResponse struct {
}

func apiIndexHandler(r *http.Request) interface{} {
coreClone := *core.App
_, err := getJwtToken(r)
if err == nil {
coreClone.LoggedIn = true
coreClone.IsAdmin = IsAdmin(r)
}
return coreClone
return core.App
}

func apiRenewHandler(w http.ResponseWriter, r *http.Request) {
Expand All @@ -50,6 +44,18 @@ func apiRenewHandler(w http.ResponseWriter, r *http.Request) {
returnJson(output, w, r)
}

func apiUpdateOAuthHandler(w http.ResponseWriter, r *http.Request) {
var c core.OAuth
err := DecodeJSON(r, &c)
if err != nil {
sendErrorJson(err, w, r)
return
}
app := core.App
app.OAuth = c
sendJsonAction(app.OAuth, "update", w, r)
}

func apiOAuthHandler(r *http.Request) interface{} {
app := core.App
return app.OAuth
Expand Down Expand Up @@ -78,7 +84,6 @@ func apiCoreHandler(w http.ResponseWriter, r *http.Request) {
if c.Domain != app.Domain {
app.Domain = c.Domain
}
app.OAuth = c.OAuth
app.UseCdn = null.NewNullBool(c.UseCdn.Bool)
app.AllowReports = null.NewNullBool(c.AllowReports.Bool)
utils.SentryInit(nil, app.AllowReports.Bool)
Expand Down
Loading

0 comments on commit 42e1b02

Please sign in to comment.