[英]Ruby Sinatra - Authenticate user against local user database (linux / mac)
Is it possible to authenticate user against the local user database on linux/mac? 是否可以针对linux / mac上的本地用户数据库对用户进行身份验证? I would like to create users locally on linux and then force authentication using sinatra or any other suggested ruby gem (no rails knowledge :()
我想在linux上本地创建用户,然后使用sinatra或任何其他建议的ruby gem强制进行身份验证(没有rails知识:()
I don't have any database and my app is so simple it should look like this: 我没有任何数据库,我的应用程序是如此简单,因此应如下所示:
require 'sinatra'
use Rack::Auth::Basic, "Restricted Area" do |username, password|
[username, password] == ['admin', 'admin']
end
get '/' do
"You're welcome"
end
My recommendation is to use a database. 我的建议是使用数据库。 If you end up going that route here is how you would do it:
如果您最终选择了这条路线,请按照以下步骤操作:
Add to your gemfile gem 'sqlite'
and gem 'sinatra-activerecord'
Run the command bundle exec rake db:create_migration NAME=setup_users_table
. 添加到您的gemfile gem'sqlite
gem 'sqlite'
和gem'sinatra gem 'sinatra-activerecord'
运行命令bundle exec rake db:create_migration NAME=setup_users_table
。 This will create a db
directory containing migrations/<random numbers>_setup_users_table.rb
. 这将创建一个包含
migrations/<random numbers>_setup_users_table.rb
的db
目录。 In that file, add code inside the change
function. 在该文件中,在
change
函数内添加代码。 To create a Users table with a username and password field add the following code: 要创建带有用户名和密码字段的Users表,请添加以下代码:
create_table :users do |i|
i.string :username
i.string :password
end
Now run bundle exec rake db:migrate
. 现在运行
bundle exec rake db:migrate
。 If that has succeded then you have a working database. 如果成功,则您有一个正常工作的数据库。 To access it you need to add to your app file the following code:
要访问它,您需要将以下代码添加到您的应用文件中:
class User < ActiveRecord::Base
end
Now you're good to go! 现在您可以出发了!
To create a user: 创建用户:
User.create(username:<whatever>,password:<whatever>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.