API Updates

This commit is contained in:
Henrique Dias 2017-07-31 21:42:09 +01:00
parent bb8f7d0958
commit 5d97fd47ba
No known key found for this signature in database
GPG Key ID: 936F5EB68D786730
6 changed files with 162 additions and 162 deletions

View File

@ -6,7 +6,7 @@
<li><router-link to="/settings/global">{{ $t('settings.goTo') }} {{ $t('settings.globalSettings') }}</router-link></li>
</ul>
<form @submit="changePassword">
<form @submit="updatePassword">
<h2>{{ $t('settings.changePassword') }}</h2>
<p><input :class="passwordClass" type="password" :placeholder="$t('settings.newPassword')" v-model="password" name="password"></p>
<p><input :class="passwordClass" type="password" :placeholder="$t('settings.newPasswordConfirm')" v-model="passwordConf" name="password"></p>
@ -14,7 +14,7 @@
</form>
<form @submit="updateCSS">
<h2>{{ $t('settings.changePassword') }}</h2>
<h2>{{ $t('settings.customStylesheet') }}</h2>
<textarea v-model="css" name="css"></textarea>
<p><input type="submit" :value="$t('buttons.update')"></p>
</form>
@ -23,7 +23,7 @@
<script>
import { mapState, mapMutations } from 'vuex'
import api from '@/utils/api'
import { updateUser } from '@/utils/api'
export default {
name: 'settings',
@ -53,14 +53,19 @@ export default {
},
methods: {
...mapMutations([ 'showSuccess' ]),
changePassword (event) {
updatePassword (event) {
event.preventDefault()
if (this.password !== this.passwordConf) {
return
}
api.updatePassword(this.password).then(() => {
let user = {
ID: this.$store.state.user.ID,
password: this.password
}
updateUser(user, 'password').then(location => {
this.showSuccess(this.$t('settings.passwordUpdated'))
}).catch(e => {
this.$store.commit('showError', e)
@ -69,7 +74,12 @@ export default {
updateCSS (event) {
event.preventDefault()
api.updateCSS(this.css).then(() => {
let user = {
ID: this.$store.state.user.ID,
css: this.css
}
updateUser(user, 'css').then(location => {
this.$store.commit('setUserCSS', this.css)
this.$emit('css-updated')
this.showSuccess(this.$t('settings.stylesUpdated'))

View File

@ -68,7 +68,7 @@
<script>
import { mapMutations } from 'vuex'
import api from '@/utils/api'
import { getUser, newUser, updateUser, deleteUser } from '@/utils/api'
export default {
name: 'user',
@ -118,7 +118,7 @@ export default {
user = 'base'
}
api.getUser(user).then(user => {
getUser(user).then(user => {
this.id = user.ID
this.admin = user.admin
this.allowCommands = user.allowCommands
@ -181,7 +181,7 @@ export default {
deleteUser (event) {
event.preventDefault()
api.deleteUser(this.id).then(location => {
deleteUser(this.id).then(location => {
this.$router.push({ path: '/users' })
this.$store.commit('showSuccess', this.$t('settings.userDeleted'))
}).catch(e => {
@ -193,7 +193,7 @@ export default {
let user = this.parseForm()
if (this.$route.path === '/settings/users/new') {
api.newUser(user).then(location => {
newUser(user).then(location => {
this.$router.push({ path: location })
this.$store.commit('showSuccess', this.$t('settings.userCreated'))
}).catch(e => {
@ -203,7 +203,7 @@ export default {
return
}
api.updateUser(user).then(location => {
updateUser(user).then(location => {
this.$store.commit('showSuccess', this.$t('settings.userUpdated'))
}).catch(e => {
this.$store.commit('showError', e)

View File

@ -7,7 +7,7 @@ import zhCN from './zh_cn.yaml'
Vue.use(VueI18n)
export default new VueI18n({
locale: 'zh_cn',
locale: 'en',
fallbackLocale: 'en',
messages: {
'en': en,

View File

@ -2,7 +2,7 @@ import store from '@/store'
const ssl = (window.location.protocol === 'https:')
function removePrefix (url) {
export function removePrefix (url) {
if (url.startsWith('/files')) {
return url.slice(6)
}
@ -10,7 +10,7 @@ function removePrefix (url) {
return url
}
function fetch (url) {
export function fetch (url) {
url = removePrefix(url)
return new Promise((resolve, reject) => {
@ -33,7 +33,7 @@ function fetch (url) {
})
}
function rm (url) {
export function rm (url) {
url = removePrefix(url)
return new Promise((resolve, reject) => {
@ -54,7 +54,7 @@ function rm (url) {
})
}
function post (url, content = '') {
export function post (url, content = '') {
url = removePrefix(url)
return new Promise((resolve, reject) => {
@ -75,7 +75,7 @@ function post (url, content = '') {
})
}
function put (url, content = '') {
export function put (url, content = '') {
url = removePrefix(url)
return new Promise((resolve, reject) => {
@ -96,7 +96,7 @@ function put (url, content = '') {
})
}
function moveCopy (items, copy = false) {
export function moveCopy (items, copy = false) {
let promises = []
for (let item of items) {
@ -129,15 +129,15 @@ function moveCopy (items, copy = false) {
return Promise.all(promises)
}
function move (items) {
export function move (items) {
return moveCopy(items)
}
function copy (items) {
export function copy (items) {
return moveCopy(items, true)
}
function checksum (url, algo) {
export function checksum (url, algo) {
url = removePrefix(url)
return new Promise((resolve, reject) => {
@ -157,7 +157,7 @@ function checksum (url, algo) {
})
}
function command (url, command, onmessage, onclose) {
export function command (url, command, onmessage, onclose) {
let protocol = (ssl ? 'wss:' : 'ws:')
url = removePrefix(url)
url = `${protocol}//${window.location.host}${store.state.baseURL}/api/command${url}`
@ -168,7 +168,7 @@ function command (url, command, onmessage, onclose) {
conn.onclose = onclose
}
function search (url, search, onmessage, onclose) {
export function search (url, search, onmessage, onclose) {
let protocol = (ssl ? 'wss:' : 'ws:')
url = removePrefix(url)
url = `${protocol}//${window.location.host}${store.state.baseURL}/api/search${url}`
@ -179,7 +179,7 @@ function search (url, search, onmessage, onclose) {
conn.onclose = onclose
}
function download (format, ...files) {
export function download (format, ...files) {
let url = `${store.state.baseURL}/api/download`
if (files.length === 1) {
@ -203,7 +203,7 @@ function download (format, ...files) {
window.open(url)
}
function getUsers () {
export function getUsers () {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('GET', `${store.state.baseURL}/api/users/`, true)
@ -224,7 +224,7 @@ function getUsers () {
})
}
function getUser (id) {
export function getUser (id) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('GET', `${store.state.baseURL}/api/users/${id}`, true)
@ -245,7 +245,7 @@ function getUser (id) {
})
}
function newUser (user) {
export function newUser (user) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('POST', `${store.state.baseURL}/api/users/`, true)
@ -266,7 +266,7 @@ function newUser (user) {
})
}
function updateUser (user) {
export function updateUser (user, which) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('PUT', `${store.state.baseURL}/api/users/${user.ID}`, true)
@ -283,11 +283,15 @@ function updateUser (user) {
}
}
request.onerror = (error) => reject(error)
request.send(JSON.stringify(user))
request.send(JSON.stringify({
what: 'user',
which: (typeof which === 'string') ? which : 'all',
data: user
}))
})
}
function deleteUser (id) {
export function deleteUser (id) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('DELETE', `${store.state.baseURL}/api/users/${id}`, true)
@ -308,49 +312,7 @@ function deleteUser (id) {
})
}
function updatePassword (password) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('PUT', `${store.state.baseURL}/api/users/change-password`, true)
request.setRequestHeader('Authorization', `Bearer ${store.state.jwt}`)
request.onload = () => {
switch (request.status) {
case 200:
resolve()
break
default:
reject(request.responseText)
break
}
}
request.onerror = (error) => reject(error)
request.send(JSON.stringify({ 'password': password }))
})
}
function updateCSS (css) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('PUT', `${store.state.baseURL}/api/users/change-css`, true)
request.setRequestHeader('Authorization', `Bearer ${store.state.jwt}`)
request.onload = () => {
switch (request.status) {
case 200:
resolve()
break
default:
reject(request.responseText)
break
}
}
request.onerror = (error) => reject(error)
request.send(JSON.stringify({ 'css': css }))
})
}
function getCommands () {
export function getCommands () {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('GET', `${store.state.baseURL}/api/commands/`, true)
@ -371,7 +333,7 @@ function getCommands () {
})
}
function updateCommands (commands) {
export function updateCommands (commands) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('PUT', `${store.state.baseURL}/api/commands/`, true)
@ -392,7 +354,7 @@ function updateCommands (commands) {
})
}
function getPlugins () {
export function getPlugins () {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('GET', `${store.state.baseURL}/api/plugins/`, true)
@ -413,7 +375,7 @@ function getPlugins () {
})
}
function updatePlugins (data) {
export function updatePlugins (data) {
return new Promise((resolve, reject) => {
let request = new window.XMLHttpRequest()
request.open('PUT', `${store.state.baseURL}/api/plugins/`, true)
@ -449,8 +411,6 @@ export default {
newUser,
updateUser,
getUsers,
updatePassword,
updateCSS,
getCommands,
updateCommands,
removePrefix,

View File

@ -70,11 +70,15 @@ import (
)
var (
errUserExist = errors.New("user already exists")
errUserNotExist = errors.New("user does not exist")
errEmptyRequest = errors.New("request body is empty")
errEmptyPassword = errors.New("password is empty")
plugins = map[string]Plugin{}
errUserExist = errors.New("user already exists")
errUserNotExist = errors.New("user does not exist")
errEmptyRequest = errors.New("request body is empty")
errEmptyPassword = errors.New("password is empty")
errEmptyUsername = errors.New("username is empty")
errEmptyScope = errors.New("scope is empty")
errWrongDataType = errors.New("wrong data type")
errInvalidUpdateField = errors.New("invalid field to update")
plugins = map[string]Plugin{}
)
// FileManager is a file manager instance. It should be creating using the

184
users.go
View File

@ -11,20 +11,22 @@ import (
"github.com/asdine/storm"
)
type modifyRequest struct {
What string `json:"what"` // Answer to: what data type?
Which string `json:"which"` // Answer to: which field?
}
type modifyUserRequest struct {
*modifyRequest
Data *User `json:"data"`
}
// usersHandler is the entry point of the users API. It's just a router
// to send the request to its
func usersHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
if r.URL.Path == "/change-password" {
return usersUpdatePassword(c, w, r)
}
if r.URL.Path == "/change-css" {
return usersUpdateCSS(c, w, r)
}
// If the user is admin and the HTTP Method is not
// PUT, then we return forbidden.
if !c.User.Admin {
// If the user isn't admin and isn't making a PUT
// request, then return forbidden.
if !c.User.Admin && r.Method != http.MethodPut {
return http.StatusForbidden, nil
}
@ -61,19 +63,25 @@ func getUserID(r *http.Request) (int, error) {
// getUser returns the user which is present in the request
// body. If the body is empty or the JSON is invalid, it
// returns an error.
func getUser(r *http.Request) (*User, error) {
func getUser(r *http.Request) (*User, string, error) {
// Checks if the request body is empty.
if r.Body == nil {
return nil, errEmptyRequest
return nil, "", errEmptyRequest
}
u := &User{}
err := json.NewDecoder(r.Body).Decode(u)
// Parses the request body and checks if it's well formed.
mod := &modifyUserRequest{}
err := json.NewDecoder(r.Body).Decode(mod)
if err != nil {
return nil, err
return nil, "", err
}
return u, nil
// Checks if the request type is right.
if mod.What != "user" {
return nil, "", errWrongDataType
}
return mod.Data, mod.Which, nil
}
func usersGetHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
@ -127,11 +135,26 @@ func usersPostHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
return http.StatusMethodNotAllowed, nil
}
u, err := getUser(r)
u, _, err := getUser(r)
if err != nil {
return http.StatusBadRequest, err
}
// Checks if username isn't empty.
if u.Username == "" {
return http.StatusBadRequest, errEmptyUsername
}
// Checks if filesystem isn't empty.
if u.FileSystem == "" {
return http.StatusBadRequest, errEmptyScope
}
// Checks if password isn't empty.
if u.Password == "" {
return http.StatusBadRequest, errEmptyPassword
}
// The username, password and scope cannot be empty.
if u.Username == "" || u.Password == "" || u.FileSystem == "" {
return http.StatusBadRequest, errors.New("username, password or scope is empty")
@ -210,72 +233,73 @@ func usersDeleteHandler(c *RequestContext, w http.ResponseWriter, r *http.Reques
return http.StatusOK, nil
}
func usersUpdatePassword(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
if r.Method != http.MethodPut {
return http.StatusMethodNotAllowed, nil
}
u, err := getUser(r)
if err != nil {
return http.StatusBadRequest, err
}
if u.Password == "" {
return http.StatusBadRequest, errEmptyPassword
}
pw, err := hashPassword(u.Password)
if err != nil {
return http.StatusInternalServerError, err
}
c.User.Password = pw
err = c.FM.db.UpdateField(&User{ID: c.User.ID}, "Password", pw)
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
func usersUpdateCSS(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
if r.Method != http.MethodPut {
return http.StatusMethodNotAllowed, nil
}
u, err := getUser(r)
if err != nil {
return http.StatusBadRequest, err
}
c.User.CSS = u.CSS
err = c.FM.db.UpdateField(&User{ID: c.User.ID}, "CSS", u.CSS)
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request) (int, error) {
// New users should be created on /api/users.
if r.URL.Path == "/" {
return http.StatusMethodNotAllowed, nil
}
// Gets the user ID from the URL and checks if it's valid.
id, err := getUserID(r)
if err != nil {
return http.StatusInternalServerError, err
}
u, err := getUser(r)
// Checks if the user has permission to access this page.
if !c.User.Admin && id != c.User.ID {
return http.StatusForbidden, nil
}
// Gets the user from the request body.
u, which, err := getUser(r)
if err != nil {
return http.StatusBadRequest, err
}
// The username and the filesystem cannot be empty.
if u.Username == "" || u.FileSystem == "" {
return http.StatusBadRequest, errors.New("Username, password or scope are empty")
// Updates the CSS.
if which == "css" {
c.User.CSS = u.CSS
err = c.FM.db.UpdateField(&User{ID: c.User.ID}, "CSS", u.CSS)
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
// Updates the Password.
if which == "password" {
if u.Password == "" {
return http.StatusBadRequest, errEmptyPassword
}
pw, err := hashPassword(u.Password)
if err != nil {
return http.StatusInternalServerError, err
}
c.User.Password = pw
err = c.FM.db.UpdateField(&User{ID: c.User.ID}, "Password", pw)
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
// If can only be all.
if which != "all" {
return http.StatusBadRequest, errInvalidUpdateField
}
// Checks if username isn't empty.
if u.Username == "" {
return http.StatusBadRequest, errEmptyUsername
}
// Checks if filesystem isn't empty.
if u.FileSystem == "" {
return http.StatusBadRequest, errEmptyScope
}
// Initialize rules if they're not initialized.
@ -288,31 +312,33 @@ func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
u.Commands = []string{}
}
var ouser *User
// Gets the current saved user from the in-memory map.
var suser *User
for _, user := range c.FM.Users {
if user.ID == id {
ouser = user
suser = user
break
}
}
if ouser == nil {
if suser == nil {
return http.StatusNotFound, nil
}
u.ID = id
if u.Password == "" {
u.Password = ouser.Password
} else {
// Changes the password if the request wants it.
if u.Password != "" {
pw, err := hashPassword(u.Password)
if err != nil {
return http.StatusInternalServerError, err
}
u.Password = pw
} else {
u.Password = suser.Password
}
// Default permissions if current are nil.
if u.Permissions == nil {
u.Permissions = c.FM.DefaultUser.Permissions
}
@ -326,8 +352,8 @@ func usersPutHandler(c *RequestContext, w http.ResponseWriter, r *http.Request)
// If the user changed the username, delete the old user
// from the in-memory user map.
if ouser.Username != u.Username {
delete(c.FM.Users, ouser.Username)
if suser.Username != u.Username {
delete(c.FM.Users, suser.Username)
}
c.FM.Users[u.Username] = u