All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.jee.api.cassandra.GetSession Maven / Gradle / Ivy

/**
 * Creative commons Attribution-NonCommercial license.
 *
 * http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB
 *
 * NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
 */
package base.jee.api.cassandra;

import java.io.IOException;

import base.Query;
import base.jee.api.Settings;
import base.security.User;

import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.PreparedStatement;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


import static base.jee.api.cassandra.util.Log.log;

/**
 * Lookup a small set of information about the person associated
 * this token and reset the expriry time of the token. This is
 * the minimal set of data that a user facing client (web page,
 * or iPhone) might need to render the user interface, such as
 * the menu bar.
 */
public class GetSession extends Query {

	private CassandraAPI c;
	private String token;

	public GetSession(CassandraAPI c, String token) {

		if(c == null) {
			throw new IllegalArgumentException("Invalid parameter: c");
		}

		this.c = c;
		this.token = token == null?null:token.trim();
	}

	public GetSession() {
	}

	@Override
	public Query newWithParameters(Map parameters) {
		return new GetSession(
				(CassandraAPI)parameters.get("api"),
				((User)parameters.get("user")).getToken());
	}

	public List execute() throws IOException {
		List results = new LinkedList<>();

		if(token == null || token.length() == 0) {
			User u = new User(null);
			u.setPersonUuid(null);
			u.setFirstName("");
			u.setLastName("");
			results.add(u);
			return results;
		}

		Settings settings = c.getSettingsCache();
		Session s = c.getCassandraSession();

		PreparedStatement q = s.prepare(
				"select person_uuid, first_name, last_name, roles " +
				"from session_token " +
				"where uid = ?");
		User u = new User(token);
		for(Row r : s.execute(q.bind(token))) {
			u.setPersonUuid(r.getUUID(0));
			u.setFirstName(r.getString(1));
			u.setLastName(r.getString(2));
			u.setRoles(r.getString(3));
			results.add(u);

			q = s.prepare(
					"update session_token " +
					"set expiry = ? " +
					"where uid = ?");
			s.execute(q.bind((new Date()).getTime()/1000 + Long.parseLong(settings.get("session.expiry")), token));

			log(s, "DEBUG", u, "Fetched session details.");

			return results;
		}

		u.setPersonUuid(null);
		u.setFirstName("");
		u.setLastName("");
		results.add(u);
		log(s, "DEBUG", u, "Fetched session details. (Non authenticated device)");
		return results;
	}

	@Override
	public String getJsonParameters() {
		return "{" +
				"\"token\":\"" + token + "\"" +
				"}";
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy