• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript bcrypt.hashSync函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中bcrypt.hashSync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript hashSync函数的具体用法?TypeScript hashSync怎么用?TypeScript hashSync使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了hashSync函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: create

	function create(): void {
		const screenName: string = req.body['screen-name'];
		const password: string = req.body['password'];

		if (screenName === undefined || screenName === null || !/^[a-zA-Z0-9\-]{2,15}$/.test(screenName)) {
			res.sendStatus(400);
			return;
		}

		if (password === undefined || password === null || password.length < 8) {
			res.sendStatus(400);
			return;
		}

		// Generate hash of password
		const salt = bcrypt.genSaltSync(14);
		const encryptedPassword = bcrypt.hashSync(password, salt);

		User.create({
			screenName: screenName,
			screenNameLower: screenName.toLowerCase(),
			encryptedPassword: encryptedPassword
		}, (err, user) => {
			if (err !== null) {
				console.error(err);
				res.sendStatus(500);
				return;
			}

			res.sendStatus(200);
		});
	}
开发者ID:syuilo,项目名称:ssmato.me,代码行数:32,代码来源:create.ts


示例2: initialize

    /**
	 * Initializes the comms controller
	 */
    async initialize( db: mongodb.Db ): Promise<void> {
        let cfg = this._cfg;

        // Throw error if no socket api key
        if ( !cfg.websocket.socketApiKey )
            throw new Error( 'The socketApiKey was not set in the config file. Make sure it exists (Check the example-config.json) ' );

        this._hashedApiKey = bcrypt.hashSync( cfg.websocket.socketApiKey, 10 );

        // dummy request processing - this is not actually called as its handed off to the socket api
        const processRequest = function( req, res ) {
            req; // Suppress compiler warning
            res.writeHead( 200 );
            res.end( 'All glory to WebSockets!\n' );
        };

        // Create the web socket server
        if ( cfg.websocket.ssl ) {
            info( 'Creating secure socket connection' );
            let httpsServer: https.Server;
            const caChain = [ fs.readFileSync( cfg.websocket.ssl.intermediate ), fs.readFileSync( cfg.websocket.ssl.root ) ];
            const privkey = cfg.websocket.ssl.key ? fs.readFileSync( cfg.websocket.ssl.key ) : null;
            const theCert = cfg.websocket.ssl.cert ? fs.readFileSync( cfg.websocket.ssl.cert ) : null;

            info( `Attempting to start Websocket server with SSL...` );
            httpsServer = https.createServer( { key: privkey, cert: theCert, passphrase: cfg.websocket.ssl.passPhrase, ca: caChain }, processRequest );
            httpsServer.listen( cfg.websocket.port );
            this._server = new ws.Server( { host: cfg.websocket.host, server: httpsServer } );
        }
        else {
            info( 'Creating regular socket connection' );
            this._server = new ws.Server( { host: cfg.websocket.host, port: cfg.websocket.port } );
        }

        info( 'Websockets attempting to listen on HTTP port ' + this._cfg.websocket.port );

        // Handle errors
        this._server.on( 'error', ( err ) => {
            logError( 'Websocket error: ' + err.toString() );
            this._server.close();
        } );

        // A client has connected to the server
        this._server.on( 'connection', ( ws: ws ) => {
            this.onWsConnection( ws );
        } );

        // Setup the socket API
        new SocketAPI( this );
    }
开发者ID:Webinate,项目名称:modepress,代码行数:53,代码来源:comms-controller.ts


示例3: createUser

export async function createUser(server: Server, request: Request, reply: IReply)
{
    const payload = request.payload as {name: string, username: string, password: string, accountId: string};
    const account = await Accounts.Database.get<Account>(payload.accountId.toLowerCase());

    if (!account)
    {
        return reply(notAcceptable(`No account with id of ${payload.accountId} exists.`));
    }

    // Ensure adding another user won't go over the account's plan limit.
    const userCount = await Users.countByAccountId(payload.accountId.toLowerCase());
    const plan = findPlan(account.planId);
    
    if (userCount >= plan.totalUsers)
    {
        return reply(notAcceptable("Account's plan has reached its maximum number of users."));
    }

    let user: User = {
        _id: payload.username,
        _rev: undefined,
        accountId: payload.accountId.toLowerCase(),
        hashedPassword: hashSync(payload.password, 10),
        name: payload.name,
    }

    try
    {
        const update = await Users.Database.put(user);

        if (!update.ok)
        {
            return reply(expectationFailed("Failed to create user.", update));
        }

        user._rev = update.rev;
    }
    catch (e)
    {
        console.error("Error thrown when creating user", e);

        throw e;
    }

    // Do not reflect the user's hashedPassword.
    user.hashedPassword = undefined;

    return reply(user).code(201);
}
开发者ID:nozzlegear,项目名称:stages-api,代码行数:50,代码来源:users-routes.ts


示例4: function

updateRecord = async function(id,data, model){
    let
    user,
    res;

    try {
        user = await model.$findById('id', id, [1]);
    } catch(err) {
        return Promise.reject(err);
    }

    try {
        res  = await bcrypt.compareSync(`|-:${data.oldpwd}:-|`, user.password);

        if(!res)
            return errors.error({
                code  : '104'
            });

        let
        _salt = bcrypt.genSaltSync(12),
        _pwd  = bcrypt.hashSync(`|-:${data.newpwd}:-|`, _salt);

        /** TODO 此处用以下方式更新 password 会提示:
            ValidationError: user validation failed

            user.password = _pwd;
            user = await user.save();
        */

        let
        update = await model.update({
            _id : user._id
        }, {
            $set : {
                password : _pwd
            }
        }).exec();

        return update.ok === 1 ? errors.success(true) : errors.error({
            code : '31'
        });
    } catch(err) {
        return Promise.reject(err);
    }

};
开发者ID:goumang2010,项目名称:NetTxtNote,代码行数:47,代码来源:static.resetPassword.ts


示例5:

const postRegister = (req, res) => {
    if (typeof req.user !== 'undefined') {
        res.redirect('/account');
        return;
    }

    if (!validateEmail(req.param('email'))) {
        req.flash('error', 'Not a valid email address!');
        res.redirect('/register');

        return;
    }

    if (req.param('password') !== req.param('password2')) {
        req.flash('error', 'Passwords do not match!');
        res.redirect('/register');

        return;
    }

    db.saveUser({
        identity: req.param('email'),
        name: req.param('name'),
        secret: bcrypt.hashSync(req.param('password'), 8)
    }, (err, saved) => {
        // TODO: log.debug("[DEBUG][/register][saveUser] %s", saved);

        if (err) {
            req.flash('error', 'There was an error creating the account. Please try again later.');
            res.redirect('/register');

            return;
        }

        if (saved) {
            log.debug("[DEBUG][/register][saveUser] /topics");
            res.redirect('/topics');
        }
        else {
            req.flash('error', 'The account wasn\'t created');
            res.redirect('/register');
            log.debug("[DEBUG][/register][saveUser] /register");
        }

        return;
    });
};
开发者ID:thinkrise,项目名称:Quip,代码行数:47,代码来源:profiles.ts


示例6: function

 formatRequestParams = async function (data): Promise<any> {
     data = _trim.statics.$extractParamForInsert.fn(data, inspectSchema);
     //修正phone及email的数据格式
     //const expandarr = ["phone", "email"];
     //expandarr.map(function (name) {
     //    if (data[name]) {
     //        let tmp = data[name];
     //        //将不会改变tmp
     //        data[name] = {
     //            value: tmp,
     //            verified: false
     //        };
     //    }
     //});
     //密码加盐
     let
         _salt = bcrypt.genSaltSync(10),
         _pwd = bcrypt.hashSync(`|-:${data.password}:-|`, _salt);
     data['password'] = _pwd;
     return data;
 };
开发者ID:goumang2010,项目名称:NetTxtNote,代码行数:21,代码来源:static.create.ts


示例7: moment

                cursor.next((err, row) => {
                    if (err && err.message.indexOf('No more rows ') > -1) {
                        const salt = bcrypt.genSaltSync(saltRounds);
                        if (!salt) res.status(500).end('User registration failed try again later.');
                        const hash = bcrypt.hashSync(req.body.password, salt);
                        if (!hash) res.status(500).end('User registration failed try again later.');
                        const refresh_token = crypto.randomBytes(20).toString('hex');
                        if (!refresh_token) res.status(500).end('User registration failed try again later.');
                        r.table("users").insert({ isAdmin: false, email: req.body.email, password: hash, refresh_token: refresh_token }).run(req.conn)
                            .then((result) => {
                                const exp = moment().add(3, "months").valueOf();
                                const user = { userId: result.generated_keys[0], email: req.body.email, expires: exp, refresh_token: refresh_token, access_token: jwtoken.sign({ isAdmin: false }, config.SECRET, { issuer: result.generated_keys[0], expiresIn: exp }) };
                                res.set('Content-Type', 'application/json');
                                res.json(user);
                            }, (err) => {
                                console.log(err)
                                res.status(500).end('Internal server error');
                            })
                    } else if (row) {
                        res.end('An account already exists for this email address.');
                    }

                })
开发者ID:triniwiz,项目名称:mojichat-api,代码行数:23,代码来源:users.ts


示例8: function

UserSchema.method("generateHash", function(password: string) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(10));
});
开发者ID:snyderjk,项目名称:TheCodeJo,代码行数:3,代码来源:user.ts


示例9: encryptPassword

 @BeforeCreate
 static encryptPassword(instance: Account) {
   if (instance.password) instance.password = bcrypt.hashSync(instance.password, bcrypt.genSaltSync(8));
 }
开发者ID:KShewengerz,项目名称:ngx-express-passport-setup,代码行数:4,代码来源:Account.ts


示例10: async

export default async (req: express.Request, res: express.Response) => {
	// Verify recaptcha
	const success = await recaptcha(req.body['g-recaptcha-response']);

	if (!success) {
		res.status(400).send('recaptcha-failed');
		return;
	}

	const username = req.body['username'];
	const password = req.body['password'];
	const name = '名無し';

	// Validate username
	if (!validateUsername(username)) {
		res.sendStatus(400);
		return;
	}

	// Fetch exist user that same username
	const usernameExist = await User
		.count({
			username_lower: username.toLowerCase()
		}, {
			limit: 1
		});

	// Check username already used
	if (usernameExist !== 0) {
		res.sendStatus(400);
		return;
	}

	// Generate hash of password
	const salt = bcrypt.genSaltSync(14);
	const hash = bcrypt.hashSync(password, salt);

	// Generate secret
	const secret = rndstr('a-zA-Z0-9', 32);

	// Create account
	const inserted = await User.insert({
		token: secret,
		avatar_id: null,
		banner_id: null,
		birthday: null,
		created_at: new Date(),
		bio: null,
		email: null,
		followers_count: 0,
		following_count: 0,
		links: null,
		location: null,
		name: name,
		password: hash,
		posts_count: 0,
		likes_count: 0,
		liked_count: 0,
		drive_capacity: 1073741824, // 1GB
		username: username,
		username_lower: username.toLowerCase()
	});

	const account = inserted.ops[0];

	// Response
	res.send(await serialize(account));

	// Create search index
	if (config.elasticsearch.enable) {
		const es = require('../../db/elasticsearch');
		es.index({
			index: 'misskey',
			type: 'user',
			id: account._id.toString(),
			body: {
				username: username
			}
		});
	}
};
开发者ID:syuilo,项目名称:misskey-core,代码行数:81,代码来源:signup.ts



注:本文中的bcrypt.hashSync函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript bcrypt-nodejs.compare函数代码示例发布时间:2022-05-25
下一篇:
TypeScript bcrypt.hash函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap