72 lines
1.9 KiB
Ruby
72 lines
1.9 KiB
Ruby
require 'openssl'
|
|
require "base64"
|
|
|
|
post '/user/logout' do
|
|
response.delete_cookie("ribica_auth", :path => "/")
|
|
#response.delete_cookie("anonymous_user_id", :path => "/")
|
|
auid = AnonymousUser.uid
|
|
response.set_cookie('anonymous_user_id', :path=> '/', :httponly => true, :value=>auid, :expires=> Time.now + 100.year)
|
|
#Cart.find_or_create(auid, -1)
|
|
end
|
|
|
|
def encrypt(data)
|
|
cipher = OpenSSL::Cipher.new('AES-128-CBC')
|
|
cipher.encrypt
|
|
cipher.key = COOKIE_SECRET_KEY
|
|
encrypted = cipher.update(data) + cipher.final
|
|
Base64.encode64(encrypted)
|
|
end
|
|
|
|
def decrypt(data)
|
|
data = Base64.decode64(data)
|
|
cipher = OpenSSL::Cipher.new('AES-128-CBC')
|
|
cipher.decrypt
|
|
cipher.key = COOKIE_SECRET_KEY
|
|
decrypted = cipher.update(data) + cipher.final
|
|
end
|
|
|
|
post '/user/login' do
|
|
request.body.rewind
|
|
login_details = JSON.parse(request.body.read)
|
|
|
|
email = login_details['email']
|
|
password = login_details['password']
|
|
|
|
res = User.find_by(email: email).try(:authenticate, password) # => false
|
|
if res
|
|
#TODO : encrypt this cookie
|
|
val = encrypt(res.id.to_s)
|
|
response.set_cookie('ribica_auth', :path=> '/', :httponly => true, :value=>val, :expires=>Time.now+100.year)
|
|
#Cart.find_or_create(anonymous_id, res.id)
|
|
res.to_json(except: 'password_digest')
|
|
else
|
|
status 401
|
|
{:error => "email ili lozinka neispravni!"}.to_json
|
|
end
|
|
end
|
|
|
|
get '/user' do
|
|
auth = cookies['ribica_auth']
|
|
if not auth.nil?
|
|
auth = decrypt(auth)
|
|
return User.find_by(id: auth).to_json(except: 'password_digest')
|
|
end
|
|
end
|
|
|
|
post '/user' do
|
|
request.body.rewind
|
|
json = request.body.read
|
|
|
|
user = User.new()
|
|
user.from_json(json, false)
|
|
|
|
if user.save
|
|
val = encrypt(user.id.to_s)
|
|
response.set_cookie('ribica_auth', :path=> '/', :httponly => true, :value=>val, :expires=>Time.now+100.year)
|
|
user.to_json(except: 'password_digest')
|
|
else
|
|
status 400
|
|
user.errors.to_json
|
|
end
|
|
end
|