com.eywa.impl.app.rest.RESTUser.java Source code

Java tutorial

Introduction

Here is the source code for com.eywa.impl.app.rest.RESTUser.java

Source

/*
 * EYWA.COM (Eywa Commerce)
 * This program is an integrated platform with E-Commerce and Configurator system.
 * Support: Please, contact the Author on http://www.smartfeeling.org.
 * Copyright (C) 2014  Gian Angelo Geminiani
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.eywa.impl.app.rest;

import com.eywa.AppEywa;
import com.eywa.impl.app.controllers.central.Activity;
import com.eywa.impl.app.controllers.central.CentralControl;
import com.eywa.impl.app.controllers.central.Mail;
import com.eywa.impl.app.errors.Error;
import com.eywa.impl.app.errors.IErrorCodes;
import com.eywa.impl.app.mongo.entities.Session;
import com.eywa.impl.app.mongo.entities.User;
import com.eywa.impl.app.mongo.entities.items.ItemBillingUser;
import com.eywa.impl.app.mongo.services.SessionService;
import com.eywa.impl.app.mongo.services.UserService;
import com.eywa.impl.app.server.utils.MediaUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.ly.commons.cryptograph.MD5;
import org.ly.commons.logging.Logger;
import org.ly.commons.logging.util.LoggingUtils;
import org.ly.commons.remoting.rest.RESTService;
import org.ly.commons.remoting.rest.annotations.FormParam;
import org.ly.commons.remoting.rest.annotations.POST;
import org.ly.commons.remoting.rest.annotations.Path;
import org.ly.commons.util.ConversionUtils;
import org.ly.commons.util.RandomUtils;
import org.ly.commons.util.RegExUtils;
import org.ly.commons.util.StringUtils;
import org.ly.packages.mongo.impl.util.MongoUtils;

import java.util.ArrayList;
import java.util.List;

@Path("/users")
public class RESTUser extends RESTService {

    // --------------------------------------------------------------------
    //               c o n s t a n t s
    // --------------------------------------------------------------------

    private static final boolean _autoenable_users = AppEywa.getAutoenableUser();
    private static final boolean _invitation_required = AppEywa.isInvitationRequired();

    private static final String UNCHANGED = "unchanged";

    // --------------------------------------------------------------------
    //               c o n s t r u c t o r
    // --------------------------------------------------------------------

    public RESTUser() {

    }

    // --------------------------------------------------------------------
    //               p u b l i c
    // --------------------------------------------------------------------

    @POST
    @Path("/confirm")
    public DBObject confirm(@FormParam("authToken") String authToken, @FormParam("userId") String userId)
            throws Exception {
        if (super.isValidToken(authToken)) {
            final UserService srvc = new UserService();
            final DBObject user = srvc.getById(userId, false);
            if (null != user) {
                User.setEnabled(user, true);
                srvc.upsert(user);

                // creates result with limited fields
                final DBObject result = new BasicDBObject();
                User.setId(result, User.getId(user));
                User.setRealname(result, User.getRealname(user));
                User.setImage(result, MediaUtils.getAvatarUrl(User.getEmail(user)));

                return result;
            }
        }
        return null;
    }

    @POST
    @Path("/get")
    public Object get(@FormParam("authToken") String authToken, @FormParam("id") String id) throws Exception {
        DBObject result = null;
        if (super.isValidToken(authToken)) {
            final UserService srvc = new UserService();
            try {
                final boolean onlyEnabled = false;
                result = srvc.getById(id, onlyEnabled);
                if (null != result) {
                    // evaluate profiles
                    //srvc.initProfiles(result);
                    // init country
                    srvc.initCountry(result);
                }

                // set password to unchanged
                User.setPassword(result, UNCHANGED);

            } catch (Throwable ignored) {
            }
        }
        return result;
    }

    @POST
    @Path("/upsert")
    public Object upsert(@FormParam("authToken") String authToken, @FormParam("user") String hash)
            throws Exception {
        if (super.isValidToken(authToken)) {
            final UserService srvc = new UserService();

            final DBObject hash_user = MongoUtils.parseObject(hash);
            final DBObject user = srvc.getById(User.getId(hash_user), true);
            if (null != user) {

                // check password
                boolean passwordChanged = false;
                final String hash_password = User.getPassword(hash_user);
                if (StringUtils.hasText(hash_password) && !hash_password.equalsIgnoreCase(UNCHANGED)) {
                    User.setPassword(user, MD5.encode(hash_password));
                    passwordChanged = true;
                }

                MongoUtils.update(hash_user, user, new String[] { User.ID, User.BILLING, User.PASSWORD,
                        User.ENABLED, User.REMOVED, User.FINDABLE, User.COUNTRY });

                //-- billing --//
                final ItemBillingUser hash_billing = new ItemBillingUser(User.getBilling(hash_user));
                final ItemBillingUser user_billing = new ItemBillingUser(User.getBilling(user));
                ItemBillingUser.setAddress(user_billing, ItemBillingUser.getAddress(hash_billing));
                ItemBillingUser.setVat(user_billing, ItemBillingUser.getVat(hash_billing));
                ItemBillingUser.setName(user_billing, ItemBillingUser.getName(hash_billing));
                ItemBillingUser.setBrand(user_billing, ItemBillingUser.getBrand(hash_billing));
                ItemBillingUser.setPaypalUser(user_billing, ItemBillingUser.getPaypalUser(hash_billing));
                ItemBillingUser.setCurrencyCode(user_billing, ItemBillingUser.getCurrencyCode(hash_billing));

                User.setBilling(user, user_billing);

                //-- update --//
                srvc.upsert(user);

                // set password to unchanged
                User.setPassword(user, UNCHANGED);

                return user;
            }
        }
        return null;
    }

    @POST
    @Path("/signin")
    public Object signin(@FormParam("authToken") String authToken, @FormParam("username") String username,
            @FormParam("password") String password) throws Exception {
        if (super.isValidToken(authToken)) {
            final UserService srvc = new UserService();
            try {
                final String md5psw = MD5.encode(password);
                final DBObject user = srvc.signin(username, md5psw);
                if (null != user) {
                    if (User.getEnabled(user)) {
                        final String userId = User.getId(user);
                        final DBObject session = SessionService.create(userId, Session.TYPE_USER, null);
                        //-- set session --//
                        User.setSession(user, session);
                        // save session in user
                        srvc.upsertNative(user);

                        // return user
                        return prepareUser(user);// creates login session
                    } else {
                        return new Error(IErrorCodes.USER_NOT_ENABLED); // code 101
                    }
                } else {
                    return new Error(IErrorCodes.USER_WRONG_LOGIN); // code 102
                }
            } catch (Throwable t) {
                return new Error(IErrorCodes.INTERNAL_ERROR, t.toString()); // code 500
            }
        }
        return null;
    }

    @POST
    @Path("/signup")
    public Object signup(@FormParam("authToken") String authToken, @FormParam("user") String hash)
            throws Exception {
        Object result = null;
        if (super.isValidToken(authToken)) {
            try {
                final DBObject hash_user = MongoUtils.parseObject(hash);
                if (!UserService.existsUser(hash_user)) {
                    if (_invitation_required && !hasInvite(hash_user)) {
                        // you are not invited at the party!!
                        result = new Error(IErrorCodes.USER_NOT_INVITED); // code 104
                    } else {
                        if (hasEmail(hash_user) && hasPassword(hash_user)) {
                            final UserService srvc = new UserService();
                            result = srvc.signup(hash_user, _autoenable_users);

                            if (null != result) {
                                final DBObject user = (DBObject) result;

                                // send email with clear text password
                                CentralControl.dispatch(Activity.newInstance().setType(Activity.TYPE_INSERT)
                                        .setCollection(User.COLLECTION).setEntity(user));

                                // if user is not enabled, returns a message informig of email activation
                                if (!_autoenable_users) {
                                    result = new Error(IErrorCodes.USER_EMAIL_ACTIVATION); // code 105
                                } else {
                                    // create session
                                    final DBObject session = SessionService.create(User.getId(user),
                                            Session.TYPE_USER, null);
                                    //-- set session --//
                                    User.setSession(user, session);
                                    // save session in user
                                    srvc.upsertNative(user);
                                }
                            }
                        } else {
                            // incomplete data
                            result = new Error(IErrorCodes.USER_DATA_INCOMPLETE); // code 103
                        }
                    }
                } else {
                    // user already exists
                    result = new Error(IErrorCodes.USER_EXISTS); // code 100
                }
            } catch (Throwable t) {
                result = new Error(IErrorCodes.INTERNAL_ERROR, t.toString()); // code 500
            }

        }
        return result;
    }

    @POST
    @Path("/exists")
    public List<DBObject> exists(@FormParam("authToken") String authToken, @FormParam("email") String email)
            throws Exception {
        if (super.isValidToken(authToken)) {
            final UserService srvc = new UserService();
            try {
                return UserService.getByEmails(new String[] { email }, null);
            } catch (Throwable ignored) {
            }
        }
        return new ArrayList<DBObject>();
    }

    @POST
    @Path("/resetpassword")
    public Error resetPassword(@FormParam("authToken") String authToken, @FormParam("username") String username)
            throws Exception {
        if (super.isValidToken(authToken)) {
            final UserService srvc = new UserService();
            final DBObject user = UserService.getOneByEmails(new String[] { username }, null);
            if (null != user) {
                final String password = RandomUtils.random(8, RandomUtils.CHARS_LOW_NUMBERS);
                User.setPassword(user, MD5.encode(password));
                srvc.upsert(user);

                // set clear text password
                User.setPassword(user, password);

                // send email with new password
                CentralControl.dispatch(Activity.newInstance().setType(Activity.TYPE_RESET)
                        .setCollection(User.COLLECTION).setEntity(user).putData(Activity.ATTR_PASSWORD, password));

                return new Error(IErrorCodes.USER_PASSWORD_RESET); // 106
            }
        }
        return new Error(IErrorCodes.USER_EMAIL_NOT_FOUND); // 107
    }

    @POST
    @Path("/resendactivation")
    public Error resendactivation(@FormParam("authToken") String authToken, @FormParam("username") String username)
            throws Exception {
        if (super.isValidToken(authToken)) {
            final UserService srvc = new UserService();
            final DBObject user = UserService.getOneByEmails(new String[] { username }, null);
            if (null != user) {

                // send email with new password
                CentralControl.dispatch(Activity.newInstance().setType(Activity.TYPE_MAIL)
                        .putData(Activity.ATTR_MAIL_TEMPLATE_ID, Mail.MAIL_TEMPLATE_ACTIVATION_LINK)
                        .putData(Activity.ATTR_USER, user));

                return new Error(IErrorCodes.USER_EMAIL_ACTIVATION); // code 105
            }
        }
        return new Error(IErrorCodes.USER_EMAIL_NOT_FOUND); // 107
    }

    @POST
    @Path("/get_shop_template")
    public Object get_shop_template(@FormParam("authToken") String authToken, @FormParam("id") String id)
            throws Exception {
        DBObject result = null;
        if (super.isValidToken(authToken)) {
            try {
                result = UserService.getShopTemplate(id);
            } catch (Throwable ignored) {
            }
        }
        return result;
    }

    @POST
    @Path("/get_account_status")
    public Object get_account_status(@FormParam("authToken") String authToken, @FormParam("id") String id)
            throws Exception {
        DBObject result = null;
        if (super.isValidToken(authToken)) {
            try {
                result = UserService.getStatus(id);
            } catch (Throwable ignored) {
            }
        }
        return result;
    }

    @POST
    @Path("/create_child")
    public Object create_child(@FormParam("authToken") String authToken, @FormParam("userId") String userId)
            throws Exception {
        DBObject result = null;
        if (super.isValidToken(authToken)) {
            try {
                result = UserService.createChild(userId);
            } catch (Throwable ignored) {
            }
        }
        return result;
    }

    @POST
    @Path("/collaborate_to_shop")
    public Object collaborate_to_shop(@FormParam("authToken") String authToken, @FormParam("userId") String userId,
            @FormParam("shopId") String shopId, @FormParam("add") String bool_add) throws Exception {
        DBObject result = null;
        if (super.isValidToken(authToken)) {
            try {
                final boolean add = ConversionUtils.toBoolean(bool_add);
                result = UserService.collaborateToShop(add, shopId, userId);
            } catch (Throwable ignored) {
            }
        }
        return result;
    }

    // ------------------------------------------------------------------------
    //                      p r i v a t e
    // ------------------------------------------------------------------------

    private static Logger getStaticLogger() {
        return LoggingUtils.getLogger(RESTUser.class);
    }

    private static boolean exists(final DBObject user) throws Exception {
        final String id = User.getId(user);
        final String email = User.getEmail(user);
        final String password = User.getPassword(user);
        if (StringUtils.hasText(password)) {
            final UserService srvc = new UserService();
            if (StringUtils.hasText(id)) {
                return null != srvc.getById(id, false);
            }
            return null != srvc.getByEmailAndPassword(email, password);
        }
        return false;
    }

    private static boolean hasId(final DBObject user) {
        return StringUtils.hasText(User.getId(user));
    }

    private static boolean hasInvite(final DBObject user) {
        final String invitation = User.getInvitation(user);
        return null != UserService.getEnabled(invitation);
    }

    private static boolean hasEmail(final DBObject user) {
        final String email = User.getEmail(user);
        return RegExUtils.isValidEmail(email);
    }

    private static boolean hasPassword(final DBObject user) {
        return StringUtils.hasText(User.getPassword(user));
    }

    private static boolean hasLang(final DBObject user) {
        return StringUtils.hasText(User.getLang(user));
    }

    private static boolean hasImage(final DBObject user) {
        return StringUtils.hasText(User.getImage(user));
    }

    private static DBObject prepareUser(final DBObject user) throws Exception {
        final UserService srvc = new UserService();
        if (null != user) {

            //-- remove password --//
            user.put(User.PASSWORD, "");

            User.setType(user, User.encodeType(user));

            // init country
            srvc.initCountry(user);
        }
        return user;
    }

}