1 Commits

Author SHA1 Message Date
Edin Dazdarevic
cb37ff0391 stuff not ready to be pushed to master 2015-03-08 22:29:37 +01:00
9 changed files with 234 additions and 49 deletions

View File

@@ -9,6 +9,9 @@ Dir[File.dirname(__FILE__) + '/models/*.rb'].each {|file| require file }
set :bind, '0.0.0.0'
COOKIE_SECRET_KEY = "RibicaMustSucceedInshaallah"
before do
content_type :json
# TODO: before running to production change this so that only specific

View File

@@ -9,21 +9,37 @@ helpers do
end
return auid
end
def user_id
auth = cookies['ribica_auth']
if not auth.nil?
auth = decrypt(auth)
return User.find_by(id: auth).id
end
-1
end
end
get '/cart/init' do
auid = anonymous_id
Cart.find_or_create(auid, user_id).to_json
auid.to_json
end
get '/cart' do
# -1 is a placeholder for user id when we implement users
# auid will still be used in case user is not logged in
Cart.find_or_create(anonymous_id, -1).to_json
Cart.find_or_create(anonymous_id, user_id).to_json
end
# gets number of items in cart for every item
get '/cart/item' do
Cart.find_or_create(anonymous_id, -1).item_in_carts.to_json
Cart.find_or_create(anonymous_id, user_id).item_in_carts.to_json
end
update_cart_item = ->() {
cart_id = Cart.find_or_create(anonymous_id, -1).id
cart_id = Cart.find_or_create(anonymous_id, user_id).id
item_id = @json_params["item_id"].to_i
count = @json_params["count"].to_i
ItemInCart.update_state(cart_id, item_id, count).to_json
@@ -34,7 +50,7 @@ post '/cart/item', &update_cart_item
# gets list of items in cart without count
get '/cart/item/display' do
cart = Cart.find_or_create(anonymous_id, -1)
cart = Cart.find_or_create(anonymous_id, user_id)
item_ids = cart.item_in_carts.map do |x|
x.item_id
end
@@ -44,12 +60,12 @@ get '/cart/item/display' do
end
get '/cart/delivery_destination' do
cart = Cart.find_or_create(anonymous_id, -1)
cart = Cart.find_or_create(anonymous_id, user_id)
cart.delivery_destination.to_json(:except => [:created_at, :email_verification_code, :phone_verification_code])
end
update_delivery_destination = ->() {
cart = Cart.find_or_create(anonymous_id, -1)
cart = Cart.find_or_create(anonymous_id, user_id)
allowed_keys = ["name", "address", "place", "postal_code", "phone", "email", "note"]
params = @json_params.reject { |key,_| !allowed_keys.include?(key) }
cart.delivery_destination.update_attributes(params)
@@ -61,10 +77,12 @@ post '/cart/delivery_destination', &update_delivery_destination
post '/cart/confirmation' do
cart = Cart.find_or_create(anonymous_id, -1)
cart = Cart.find_or_create(anonymous_id, user_id)
if cart.item_in_carts.length > 0
cart.ordered = true
cart.save!
end
Cart.find_or_create(anonymous_id, user_id)
"OK".to_json
end
end

View File

@@ -1,6 +1,28 @@
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
@@ -13,7 +35,9 @@ post '/user/login' do
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)
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
@@ -24,6 +48,7 @@ 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
@@ -36,7 +61,8 @@ post '/user' do
user.from_json(json, false)
if user.save
response.set_cookie('ribica_auth', :path=> '/', :httponly => true, :value=>user.id, :expires=>Time.now+100.year)
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

View File

@@ -2,12 +2,104 @@ class Cart < ActiveRecord::Base
has_many :item_in_carts, -> { order "created_at" }
belongs_to :delivery_destination
def self.find_or_create(anonymous_id, user_id)
cart = Cart.where(user_id: user_id).where(ordered: false).first
cart ||= Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
safe_user_id = (user_id > 0) ? user_id : nil
cart ||= Cart.create!(anonymous_id_string: anonymous_id, user_id: safe_user_id, ordered: false )
cart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
return cart
def self.get_current(anonymous_id, user_id)
safe_user_id = (user_id > 0) ? user_id : nil
if user_id > 0
uCart = Cart.where(user_id: user_id).where(ordered: false).first
uCart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
return uCart
else
anonymousCart = Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
anonymousCart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
return anonymousCart
end
end
end
def self.find_or_create(anonymous_id, user_id)
safe_user_id = (user_id > 0) ? user_id : nil
if user_id > 0
#we're logged in
# users anonymous stuff
anonymousCart = Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
# users stuff in the db, create if needed
uCart = Cart.where(user_id: user_id).where(ordered: false).first
uCart ||= Cart.create!(user_id: safe_user_id, ordered: false )
# now we have two carts for this logged in user, since he is logged in,
# we'll merge everything
if anonymousCart
# the user has an anonymous cart we need to merge it into ucart and delete it afterwards
anonymousCart.item_in_carts.each do |item|
uCart.item_in_carts << item
end
uCart.save
anonymousCart.delete
end
uCart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
return uCart
else
# we're not logged in
# get the anonymous cart, create if needed
anonymousCart = Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
anonymousCart ||= Cart.create!(anonymous_id_string: anonymous_id, user_id: safe_user_id, ordered: false )
anonymousCart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
return anonymousCart
end
# logger.debug "Cart.find_or_create"
#cart = Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
#safe_user_id = (user_id > 0) ? user_id : nil
#if cart != nil && user_id > 0
## we have anonymous cart but also a user id
## we need to merge carts
#uCart = Cart.where(user_id: user_id).where(ordered: false).first
#uCart ||= Cart.create!(user_id: safe_user_id, ordered: false )
#uCart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
#logger.debug "Cart also found with aid but now has valid user id"
#cart.item_in_carts.each do |item|
#ucart.item_in_carts << item
#end
##cart.user_id = safe_user_id
##cart.anonymous_id_string = nil
##cart.save
#uCart.save
#cart.delete
##cart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
#return uCart
#end
#if cart != nil
#return cart
#end
#cart = Cart.where(user_id: user_id).where(ordered: false).first
#if cart != nil
#logger.debug "Cart found by user_id"
#cart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
#return cart
#end
#logger.debug "Cart with aid will be used!"
#cart ||= Cart.create!(anonymous_id_string: anonymous_id, user_id: safe_user_id, ordered: false )
#cart.delivery_destination ||= DeliveryDestination.find_or_create(anonymous_id, user_id);
#return cart
end
end

View File

@@ -52,6 +52,13 @@ var UserActions = {
AppDispatcher.handleAction({
actionType: UserConstants.USER_LOGOUT_DONE
});
NavigationActions.goToHome();
},
clearLogin: function() {
console.log('clearing login form');
AppDispatcher.handleAction({
actionType: UserConstants.USER_LOGIN_CLEAR
});
},
userLogin: function(loginDetails) {
AppDispatcher.handleAction({

View File

@@ -12,10 +12,14 @@ var Login = React.createClass({
mixins: [RibicaValidationMixin],
componentDidMount:function() {
UserStore.addChangeListener(this.onUserStoreChange);
UserActions.clearLogin();
},
componentWillUnmount: function() {
UserStore.removeChangeListener(this.onUserStoreChange);
},
componentWillReceiveProps: function() {
UserActions.clearLogin();
},
onUserStoreChange: function() {
if(this.isMounted()) {
var loginState = UserStore.getLoginState();

View File

@@ -11,5 +11,6 @@ module.exports = keyMirror({
CHECK_LOGIN: null,
CHECK_LOGIN_ARRIVED: null,
USER_LOGOUT_DONE: null,
USER_LOGOUT: null
USER_LOGOUT: null,
USER_LOGIN_CLEAR: null
});

View File

@@ -8,10 +8,12 @@ var ItemInCartCollection = require('../models/itemInCartCollection');
var ItemCollection = require('../models/itemCollection');
var DeliveryDestination = require('../models/deliveryDestination');
var OrderConfirmation = require('../models/orderConfirmation');
var globals = require('../globals');
var Superagent = require('superagent');
var _ = require('underscore');
var states = {}
var initialized = false;
var _itemsInCart = new ItemInCartCollection();
var _itemsForDisplay = new ItemCollection();
@@ -19,30 +21,53 @@ _itemsForDisplay.setFromCart(true);
var _deliveryDestination = new DeliveryDestination();
var loadCart = function() {
_itemsInCart.fetch({
success: function() {
states = {}
for (var i = 0; i < _itemsInCart.models.length; i++) {
var itemInCart = _itemsInCart.models[i];
states[itemInCart.get('item_id')] = itemInCart;
}
CartActions.dataLoaded();
}
});
_itemsForDisplay.fetch({
success: function() {
CartActions.dataLoaded();
}
})
if (!_deliveryDestination.get('id')) {
_deliveryDestination.fetch({
var loadCart = function() {
var get = function() {
_itemsInCart.fetch({
success: function() {
CartActions.dataLoaded();
states = {}
for (var i = 0; i < _itemsInCart.models.length; i++) {
var itemInCart = _itemsInCart.models[i];
states[itemInCart.get('item_id')] = itemInCart;
}
//CartActions.dataLoaded();
_itemsForDisplay.fetch({
success: function() {
//CartActions.dataLoaded();
if (!_deliveryDestination.get('id')) {
_deliveryDestination.fetch({
success: function() {
CartActions.dataLoaded();
}
});
} else {
CartActions.dataLoaded();
}
}
});
}
});
}
};
get();
//if(initialized) {
//get();
//} else {
//Superagent
//.get(globals.ApiUrl + '/cart/init')
//.withCredentials()
//.end(function(response) {
//if(response.ok) {
//initialized = true;
//get();
//}
//});
//}
};
@@ -201,4 +226,4 @@ AppDispatcher.register(function(payload) {
});
module.exports = CartStore;
module.exports = CartStore;

View File

@@ -59,6 +59,12 @@ var handleLogoutDone = function() {
}
};
var handleClearLogin = function() {
_loginState = {
loggedIn: false
}
};
// Extend SectionStore with EventEmitter to add eventing capabilities
var UserStore = _.extend({}, EventEmitter.prototype, {
@@ -97,22 +103,25 @@ AppDispatcher.register(function(payload) {
case UserConstants.REGISTRATION_SUCCESS:
handleRegistrationSuccess(action.user);
break;
break;
case UserConstants.REGISTRATION_FAILURE:
handleRegistrationFailure(action.error);
break;
break;
case UserConstants.LOGIN_SUCCESS:
handleLoginSuccess(action.user);
break;
break;
case UserConstants.LOGIN_FAILURE:
handleLoginFailure(action.error);
break;
break;
case UserConstants.CHECK_LOGIN_ARRIVED:
handleCheckLoginArrived(action.user, action.error);
break;
handleCheckLoginArrived(action.user, action.error);
break;
case UserConstants.USER_LOGOUT_DONE:
handleLogoutDone();
break;
handleLogoutDone();
break;
case UserConstants.USER_LOGIN_CLEAR:
handleClearLogin();
break;
default:
return true;
}