github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-supply-chain-master/server/db/users.js (about) 1 /** 2 * Copyright 2017 Intel Corporation 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * ---------------------------------------------------------------------------- 16 */ 17 'use strict' 18 19 const _ = require('lodash') 20 const db = require('./') 21 22 const USER_SCHEMA = { 23 username: String, 24 password: String, 25 email: /.+@.+\..+/, 26 publicKey: String, 27 '?encryptedKey': String, 28 '*': null 29 } 30 31 // Modified user schema with optional keys 32 const UPDATE_SCHEMA = _.mapKeys(USER_SCHEMA, (_, key) => { 33 if (key === '*' || key[0] === '?') return key 34 return '?' + key 35 }) 36 37 const query = query => db.queryTable('users', query) 38 39 const insert = user => { 40 return db.validate(user, USER_SCHEMA) 41 .then(() => db.insertTable('users', user)) 42 .then(results => { 43 return db.insertTable('usernames', {username: user.username}) 44 .then(() => results) 45 .catch(err => { 46 // Delete user, before re-throwing error 47 return db.modifyTable('users', users => { 48 return users.get(user.publicKey).delete() 49 }) 50 .then(() => { throw err }) 51 }) 52 }) 53 } 54 55 const update = (publicKey, changes) => { 56 return db.validate(changes, UPDATE_SCHEMA) 57 .then(() => db.updateTable('users', publicKey, changes)) 58 .then(results => { 59 // If changes did not change the resource, just fetch it 60 if (results.unchanged === 1) { 61 return db.queryTable('users', users => users.get(publicKey), false) 62 } 63 64 const oldUser = results.changes[0].old_val 65 const newUser = results.changes[0].new_val 66 67 // If username did not change, send back new users 68 if (!changes.username) return newUser 69 70 // Modify usernames table with new name 71 return db.modifyTable('usernames', usernames => { 72 return usernames.get(oldUser.username).delete().do(() => { 73 return usernames.insert({username: changes.username}) 74 }) 75 }) 76 .then(() => newUser) 77 .catch(err => { 78 // If failed to update usernames, reset user and re-throw error 79 return db.updateTable('users', publicKey, oldUser) 80 .then(() => { throw err }) 81 }) 82 }) 83 } 84 85 module.exports = { 86 query, 87 insert, 88 update 89 }