helpers do def logged_in_user_id auth = cookies['ribica_auth'] auth ||= -1 return auth.to_i end def anonymous_id auid = cookies[:anonymous_user_id] if auid.nil? auid = AnonymousUser.uid response.set_cookie('anonymous_user_id', :path=> '/', :httponly => true, :value=>auid, :expires=> Time.now + 100.year) end return auid end end post '/user/logout' do response.delete_cookie("ribica_auth", :path => "/") 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 response.set_cookie('ribica_auth', :path=> '/', :httponly => true, :value=>res.id, :expires=>Time.now+100.year) 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? 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 response.set_cookie('ribica_auth', :path=> '/', :httponly => true, :value=>user.id, :expires=>Time.now+100.year) user.to_json(except: 'password_digest') else status 400 user.errors.to_json end end