1. 程式人生 > >Saiku去掉License驗證信息以及數據備份(二十一)

Saiku去掉License驗證信息以及數據備份(二十一)

version aik conn deb day 技術分享 meteor oba error:

Saiku去掉License驗證信息

終於還是走到了這一步,老早就在說要去掉這個License驗證了,一直沒做因為忙著別的。但是因為這個License還和可定義的用戶數相關,限制了我們的使用,所以這裏從saiku源碼中做更改,去掉License驗證。

需要更改的代碼文件如下:

saiku-core\saiku-web\src\main\java\org\saiku\web\rest\resources\License.java
saiku-core\saiku-web\src\main\java\org\saiku\web\service\SessionService.java
saiku-ui\js\saiku\models\Session.js
saiku-ui\js\saiku\views\Upgrade.js

>>>後臺代碼更改  

1.更改SesseionService.java類中的 login方法,將有關於Licence驗證的代碼註釋掉即可。改完後的login方法如下:

	 * @see org.saiku.web.service.ISessionService#login(javax.servlet.http.HttpServletRequest, java.lang.String, java.lang.String)
	 */
	/**modify the login for getting rid of license validate 2019-03-29*/
	public Map<String, Object> login(HttpServletRequest req, String username, String password ) throws LicenseException {
	//	Object sl = null;
	//	String notice = null;
		HttpSession session = ((HttpServletRequest)req).getSession(true);
		session.getId();
		sessionRepo.setSession(session);
//		try {
//			sl = l.getLicense();
//		} catch (Exception e) {
//			log.debug("Could not process license", e);
//			throw new LicenseException("Error fetching license. Get a free license from http://licensing.meteorite.bi. You can upload it at /upload.html");
//		}

//		if (sl != null) {

//			try {
//				l.validateLicense();
//			} catch (RepositoryException | IOException | ClassNotFoundException e) {
//				log.debug("Repository Exception, couldn‘t get license", e);
//				throw new LicenseException("Error fetching license. Please check your logs.");
//			}

			if (authenticationManager != null) {
			    authenticate(req, username, password);
			}
			if (SecurityContextHolder.getContext() != null
			    && SecurityContextHolder.getContext().getAuthentication() != null) {
			    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

			    if (authorisationPredicate.isAuthorised(auth)) {
			        Object p = auth.getPrincipal();
			        createSession(auth, username, password);
			        return sessionHolder.get(p);
			    } else {
			        log.info(username + " failed authorisation. Rejecting login");
			        throw new RuntimeException("Authorisation failed for: " + username);
			    }
			}
			return new HashMap<>();
	}
	

  

2.更改License.java類中的getLicense方法,將License校驗直接返回正確的結果。 改動後的代碼getLicense方法如下:

 @GET
  @Produces({ "application/json" })
  public Response getLicense() {
//    try {
//      return Response.ok().entity(licenseUtils.getLicense()).build();
//    } catch (IOException | RepositoryException | ClassNotFoundException e) {
//      e.printStackTrace();
//    }
    return Response.serverError().build();
  }

  

>>>前端代碼更改

3. 去掉Saiku升級相關提示,Upgrade.js文件中將render方法內容註釋掉,詳情如下:

render: function() {
/*
		var self = this;
		var license = new License();

		if(Settings.BIPLUGIN5){
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>Notice:"+Saiku.session.get("notice")+"</div>");

				}
				if (Settings.LICENSE.licenseType != undefined && (Settings.LICENSE.licenseType != "trial" && Settings.LICENSE.licenseType != "Open Source License")) {
					return this;
				}
				if (Settings.LICENSE != undefined && Settings.LICENSE.licenseType === "trial") {
					var yourEpoch = parseFloat(Settings.LICENSE.expiration);
					var yourDate = new Date(yourEpoch);
					self.remainingdays = self.daydiff(new Date(), yourDate);


					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using a Saiku Enterprise" +
						" Trial license, you have "+ self.remainingdays+" days remaining. <a href=‘http://www.meteorite.bi/saiku-pricing‘>Buy licenses online.</a></div>");
					return self;
				}
				else {
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using Saiku Community" +
						" Edition, please consider upgrading to <a target=‘_blank‘ href=‘http://meteorite.bi‘>Saiku Enterprise</a>, or entering a <a href=‘http://meteorite.bi/products/saiku/sponsorship‘>sponsorship agreement with us</a> to support development. " +
						"<a href=‘http://meteorite.bi/products/saiku/community‘>Or contribute by joining our community and helping other users!</a></div></div>");

					return self;
				}
		}
		else {
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>Notice:"+Saiku.session.get("notice")+"</div>");

				}
				if (Settings.LICENSE.licenseType != undefined && (Settings.LICENSE.licenseType != "trial" &&
					Settings.LICENSE.licenseType != "Open Source License")) {
					return this;
				}
				if (Settings.LICENSE.licenseType === "trial") {
					var yourEpoch = parseFloat(Settings.LICENSE.expiration);
					var yourDate = new Date(yourEpoch);

					self.remainingdays = self.daydiff(new Date(), yourDate);

					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using a Saiku Enterprise" +
						" Trial license, you have "+ self.remainingdays+" days remaining. <a href=‘http://www.meteorite.bi/saiku-pricing‘>Buy licenses online.</a></div>");
					return self;
				}
				else {
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using Saiku Community" +
						" Edition, please consider upgrading to <a target=‘_blank‘ href=‘http://meteorite.bi‘>Saiku Enterprise</a>, or entering a <a href=‘http://meteorite.bi/products/saiku/sponsorship‘>sponsorship agreement with us</a> to support development. " +
						"<a href=‘http://meteorite.bi/products/saiku/community‘>Or contribute by joining our community and helping other users!</a></div></div>");
					return self;
				}
		}




*/



	},

  

4.為了防止前臺console中出現調用License接口404錯誤,我們還需要更改一下 Session.js的process_session與check_session方法,使其不調用License

 check_session: function() {
		// This authentication cookie is used only by Orbis authentication strategy
		var authCookie = this.getCookie(Settings.ORBIS_AUTH.cookieName);

		if (Settings.ORBIS_AUTH.hazelcast_enabled && authCookie && !this.atemptedToLoginByCookie) {
            this.sessionid               = 1;
            this.username                = authCookie;
            this.password                = authCookie;
            this.atemptedToLoginByCookie = true;

            // In this case we inject the proper license attributes
            var ONE_YEAR = 31556952000;
            
            /**
            Settings.LICENSE = {
              licenseType: ‘Orbis‘,
              expiration: Date.now() + ONE_YEAR
            }
            */
            this.login(authCookie, authCookie);
		} else {
			if (this.sessionid === null || this.username === null || this.password === null) {
				var that = this;
				this.clear();
				this.fetch({ success: this.process_session, error: this.brute_force });
			} else {
                if (!this.atemptedToLoginByCookie) {
                    this.username = encodeURIComponent(options.username);
                }

				this.load_session();
			}
		}
    },

 process_session: function(model, response) {
        if ((response === null || response.sessionid == null)) {
            // Open form and retrieve credentials
            Saiku.ui.unblock();
            if (Settings.DEMO) {
                this.form = new DemoLoginForm({ session: this });
            } else {
                this.form = new LoginForm({ session: this });
            }
            this.form.render().open();
        } else {
            this.sessionid = response.sessionid;
            this.roles = response.roles;
            this.isAdmin = Settings.ORBIS_AUTH.hazelcast_enabled || response.isadmin;
            this.username = encodeURIComponent(response.username);
            this.language = response.language;
            if (typeof this.language != "undefined" && this.language != Saiku.i18n.locale) {
                Saiku.i18n.locale = this.language;
                Saiku.i18n.automatic_i18n();
            }
            /**
                var license =new License();

                license.fetch_license(‘api/license/‘, function(opt) {
                    if (opt.status === ‘success‘) {
                        Settings.LICENSE = opt.data.toJSON();
                    }
                    if(Saiku.session.isAdmin) {

                        var quota = new LicenseQuota();

                        quota.fetch_quota(‘api/license/quota‘, function (opt) {
                            if (opt.status === ‘success‘) {
                                Settings.LICENSEQUOTA = opt.data.toJSON();
                            }
                        });
                    }

                });
			*/

            this.load_session();
        }

        return this;
    },

  

做出以上更改後,重新打包編譯源碼即可。

再次啟動編譯好的saiku,就會發現不需要上傳License文件啦!可直接登錄saiku進行使用~

而且還有個地方可以驗證你是否已經成功取得License相關信息,使用admin登錄控制管理臺,看不到license就表示成功了!!

技術分享圖片

>>> Saiku數據備份

關於saiku的數據備份,今日份嘗試了一下,只需要將saiku-server目錄下的 data,repository目錄備份即可。(如果對saiku的源碼有改動,重新編譯了saiku ,建議將正在使用的saiku相關數據保存下來,免得自己再去配置。)

可直接去替換重新編譯好的data , repository目錄,在啟動saiku,就會發現之前配置好的數據以及用戶角色信息、文件信息都完好的保存了啦!!! 這就很贊啦嘻嘻嘻

技術分享圖片

最後提供一下被更改過的完整的文件信息:(可直接用來替換本地的這個四個文件哦)

saiku-core\saiku-web\src\main\java\org\saiku\web\rest\resources\License.java

/* Copyright (C) OSBI Ltd - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by OSBI LTD, 2014
 */

package org.saiku.web.rest.resources;

import org.saiku.service.license.ILicenseUtils;
import org.saiku.database.Database;
import org.saiku.service.license.Base64Coder;
import org.saiku.service.user.UserService;
import org.saiku.web.rest.objects.UserList;

import com.qmino.miredot.annotations.ReturnType;

import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.jcr.RepositoryException;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;

/**
 * Saiku license information resource.
 *
 * @since 3.0
 * @author tbarber
 */
@Component
@Path("/saiku/api/license")
public class License {

  private ILicenseUtils licenseUtils;
  private UserService userService;

  public ILicenseUtils getLicenseUtils() {
    return licenseUtils;
  }

  public void setLicenseUtils(ILicenseUtils licenseUtils) {
    this.licenseUtils = licenseUtils;
  }

  private Database databaseManager;

  public Database getDatabaseManager() {
    return databaseManager;
  }

  public void setDatabaseManager(Database databaseManager) {
    this.databaseManager = databaseManager;
  }

  public void setUserService(UserService us) {
    userService = us;
  }

  /**
   * Get the saiku
   * @summary Get the Saiku License installed on the current server
   * @return A response containing a license object.
   */
  @GET
  @Produces({ "application/json" })
  public Response getLicense() {
//    try {
//      return Response.ok().entity(licenseUtils.getLicense()).build();
//    } catch (IOException | RepositoryException | ClassNotFoundException e) {
//      e.printStackTrace();
//    }
    return Response.serverError().build();
  }

  private static final int SIZE = 2048;


  /**
   * Upload a new license to the Saiku server.
   * @summary Upload a new license
   * @param is A license encapsulated in an input stream
   * @return An acknowledgement as to whether the server installation was successful.
   */
  @POST
  @Consumes("application/x-java-serialized-object")
  @Produces("text/plain")
  @ReturnType("java.lang.String")
  public Response saveLicense(InputStream is) {
    ObjectInputStream si = null;
    byte[] sig;
    byte[] data = null;
    try {
      si = new ObjectInputStream(is);
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      int sigLength = si.readInt();
      sig = new byte[sigLength];
      si.read(sig);

      ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
      byte[] buf = new byte[SIZE];
      int len;
      while ((len = si.read(buf)) != -1) {
        dataStream.write(buf, 0, len);
      }
      dataStream.flush();
      data = dataStream.toByteArray();
      dataStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        si.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }


    getLicenseUtils().setLicense(new String(Base64Coder.encode(data)));

    return Response.ok("License Upload Successful").build();
  }

  /**
   * Validate the license installed on the server.
   * @summary License validation
   * @return A response indicating whether the operation was successful.
   */
  @GET
  @Path("/validate")
  @Produces({ "text/plain" })
  @ReturnType("java.lang.String")
  public Response validateLicense() {
//    if(!userService.isAdmin()){
//      return Response.status(Response.Status.FORBIDDEN).build();
//    }
//    try {
//      licenseUtils.validateLicense();
//    } catch (IOException e) {
//      e.printStackTrace();
//      return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
//                     .entity(e.getLocalizedMessage()).build();
//    } catch (ClassNotFoundException e) {
//      e.printStackTrace();
//      return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
//                     .entity(e.getLocalizedMessage()).build();
//    } catch (LicenseException e) {
//      return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
//                     .entity(e.getLocalizedMessage()).build();
//    } catch (RepositoryException e) {
//      return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
//                     .entity("Could not find license file").build();
//    } catch (Exception e) {
//      e.printStackTrace();
//    }
    return Response.ok().entity("Valid License").build();


  }


  /**
   * Get the current user list from the server.
   * @summary Get the user list
   * @return A list of users.
   */
  @GET
  @Path("/usercount")
  @Produces({"application/json"})
  @ReturnType("java.util.ArrayList<UserList>")
  public Response getUserCount(){
    if(!userService.isAdmin()){
      return Response.status(Response.Status.FORBIDDEN).build();
    }
    try {
      List<String> l = getAuthUsers();
      if(l!=null) {
        List<UserList> ul = new ArrayList();
        int i = 0;
        for (String l2 : l) {
          ul.add(new UserList(l2, i));
          i++;
        }
        return Response.ok().entity(ul.size()).build();
      }
    } catch (SQLException e) {
      e.printStackTrace();
      return Response.ok().entity(0).build();
    }
    return Response.ok().entity(0).build();
  }

  /**
   * Get the current user list from the server.
   * @summary Get the user list
   * @return A list of users.
   */
  @GET
  @Path("/users")
  @Produces({"application/json"})
  @ReturnType("java.util.ArrayList<UserList>")
  public Response getUserlist(){
    if(!userService.isAdmin()){
      return Response.status(Response.Status.FORBIDDEN).build();
    }
    try {
      List<String> l = getAuthUsers();
      if(l!=null) {
        List<UserList> ul = new ArrayList();
        int i = 0;
        for (String l2 : l) {
          ul.add(new UserList(l2, i));
          i++;
        }
        return Response.ok().entity(ul).build();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * Upload a user list to the server.
   * @summary Upload user list
   * @param l A List of UserList objects
   * @return A response indicating whether the operation was successful.
   */
  @POST
  @Path("/users")
  @Produces({"text/plain"})
  @Consumes({"application/json"})
  @ReturnType("java.lang.String")
  public Response createUserList(List<UserList> l){
    try {
      List<String> l3 = new ArrayList<>();
      for(UserList l2 : l){
        l3.add(l2.getName());
      }
      addUsers(l3);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return Response.ok().entity("List created").build();

  }

  /**
   * Update the list of users with new users.
   * @summary Update user list
   * @param l A list of UserList objects
   * @return A response indicating whether the operation was successful.
   */
  @PUT
  @Path("/users")
  @Produces({"text/plain"})
  @Consumes({"application/json"})
  @ReturnType("java.lang.String")
  public Response updateUserList(List<UserList> l){
    try {
      List<String> l3 = new ArrayList<>();
      for(UserList l2 : l){
        l3.add(l2.getName());
      }
      updateUsers(l3);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return Response.ok().entity("List updated").build();

  }

  /**
   * Delete the user list from the server.
   * @summary Delete user list.
   * @return A response indicating whether the operation was successful.
   */
  @DELETE
  @Path("/users")
  @Produces({"application/json"})
  @ReturnType("java.lang.String")
  public Response deleteUserlist(){

    try {
      List<String> l = getAuthUsers();
      List<UserList> ul = new ArrayList<>();
      int i = 0;
      for(String l2 : l) {
        ul.add(new UserList(l2, i));
        i++;
      }
      return Response.ok().entity(ul).build();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * Get the valid users from the database.
   * @return a list of usernames
   * @throws SQLException
   */
  private List<String> getAuthUsers() throws SQLException {
    return databaseManager.getUsers();
  }

  /**
   * Get the user quota for existing users with no license
   * @return a list of user quota.
   */
  @GET
  @Produces("application/json")
  @Path("/quota")
  @ReturnType("java.util.List<UserQuota>")
  public Response getUserQuota(){
    if(!userService.isAdmin()){
      return Response.status(Response.Status.FORBIDDEN).build();
    }
    return Response.ok().entity(100000000).build();
  }


  /**
   * Add users to the database.
   * @param l List of usernames
   * @throws SQLException
   */
  public void addUsers(List<String> l) throws SQLException {
    databaseManager.addUsers(l);
  }

  /**
   * Add users to the database.
   * @param l List of usernames
   * @throws SQLException
   */
  public void updateUsers(List<String> l) throws SQLException {
    databaseManager.addUsers(l);
  }

}

  

saiku-core\saiku-web\src\main\java\org\saiku\web\service\SessionService.java

/*  
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package org.saiku.web.service;

import org.apache.commons.lang.StringUtils;
import org.saiku.repository.ScopedRepo;
import org.saiku.service.ISessionService;
import org.saiku.service.license.ILicenseUtils;

import bi.meteorite.license.LicenseException;
import bi.meteorite.license.SaikuLicense2;
import org.saiku.service.util.security.authorisation.AuthorisationPredicate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.context.request.RequestContextHolder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


public class SessionService implements ISessionService {

	private static final Logger log = LoggerFactory.getLogger(SessionService.class);

	private AuthenticationManager authenticationManager;
	private AuthorisationPredicate authorisationPredicate;

	private final Map<Object,Map<String,Object>> sessionHolder = new HashMap<>();

	private Boolean anonymous = false;
	private ScopedRepo sessionRepo;
	private Boolean orbisAuthEnabled = false;

	public void setAllowAnonymous(Boolean allow) {
		this.anonymous  = allow;
	}

	private ILicenseUtils l;

	public ILicenseUtils getL() {
		return l;
	}

	public void setL(ILicenseUtils l) {
		this.l = l;
	}

	/* (non-Javadoc)
         * @see org.saiku.web.service.ISessionService#setAuthenticationManager(org.springframework.security.authentication.AuthenticationManager)
         */
	public void setAuthenticationManager(AuthenticationManager auth) {
		this.authenticationManager = auth;
	}

	public void setAuthorisationPredicate(AuthorisationPredicate authorisationPredicate)
	{
		this.authorisationPredicate = authorisationPredicate;
	}

	/* (non-Javadoc)
	 * @see org.saiku.web.service.ISessionService#login(javax.servlet.http.HttpServletRequest, java.lang.String, java.lang.String)
	 */
	/**modify the login for getting rid of license validate 2019-03-29*/
	public Map<String, Object> login(HttpServletRequest req, String username, String password ) throws LicenseException {
	//	Object sl = null;
	//	String notice = null;
		HttpSession session = ((HttpServletRequest)req).getSession(true);
		session.getId();
		sessionRepo.setSession(session);
//		try {
//			sl = l.getLicense();
//		} catch (Exception e) {
//			log.debug("Could not process license", e);
//			throw new LicenseException("Error fetching license. Get a free license from http://licensing.meteorite.bi. You can upload it at /upload.html");
//		}

//		if (sl != null) {

//			try {
//				l.validateLicense();
//			} catch (RepositoryException | IOException | ClassNotFoundException e) {
//				log.debug("Repository Exception, couldn‘t get license", e);
//				throw new LicenseException("Error fetching license. Please check your logs.");
//			}

			if (authenticationManager != null) {
			    authenticate(req, username, password);
			}
			if (SecurityContextHolder.getContext() != null
			    && SecurityContextHolder.getContext().getAuthentication() != null) {
			    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

			    if (authorisationPredicate.isAuthorised(auth)) {
			        Object p = auth.getPrincipal();
			        createSession(auth, username, password);
			        return sessionHolder.get(p);
			    } else {
			        log.info(username + " failed authorisation. Rejecting login");
			        throw new RuntimeException("Authorisation failed for: " + username);
			    }
			}
			return new HashMap<>();
	}
	
	/** The old login validation , have to validate license information
	public Map<String, Object> login(HttpServletRequest req, String username, String password ) throws LicenseException {
		Object sl = null;
		String notice = null;
		HttpSession session = ((HttpServletRequest)req).getSession(true);
		session.getId();
		sessionRepo.setSession(session);
		try {
			sl = l.getLicense();
		} catch (Exception e) {
			log.debug("Could not process license", e);
			throw new LicenseException("Error fetching license. Get a free license from http://licensing.meteorite.bi. You can upload it at /upload.html");
		}

		if (sl != null) {

			try {
				l.validateLicense();
			} catch (RepositoryException | IOException | ClassNotFoundException e) {
				log.debug("Repository Exception, couldn‘t get license", e);
				throw new LicenseException("Error fetching license. Please check your logs.");
			}

			try {
				if (l.getLicense() instanceof SaikuLicense2) {

                    if (authenticationManager != null) {
                        authenticate(req, username, password);
                    }
                    if (SecurityContextHolder.getContext() != null
                        && SecurityContextHolder.getContext().getAuthentication() != null) {
                        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

                        if (authorisationPredicate.isAuthorised(auth)) {
                            Object p = auth.getPrincipal();
                            createSession(auth, username, password);
                            return sessionHolder.get(p);
                        } else {
                            log.info(username + " failed authorisation. Rejecting login");
                            throw new RuntimeException("Authorisation failed for: " + username);
                        }
                    }
                    return new HashMap<>();
                }
			} catch (IOException | ClassNotFoundException | RepositoryException e) {
				log.debug("Repository Exception, couldn‘t get license", e);
				throw new LicenseException("Error fetching license. Please check your logs.");
			}
		}
		return null;
	}
*/
	private void createSession(Authentication auth, String username, String password) {

		if (auth ==  null || !auth.isAuthenticated()) {
			return;
		}
		
		boolean isAnonymousUser = (auth instanceof AnonymousAuthenticationToken);		
		Object p = auth.getPrincipal();
		String authUser = getUsername(p);
		boolean isAnonymous = (isAnonymousUser || StringUtils.equals("anonymousUser", authUser));
		boolean isAnonOk = (!isAnonymous || (isAnonymous && anonymous));
			
		if (isAnonOk && auth.isAuthenticated() && p != null && !sessionHolder.containsKey(p)) {
			Map<String, Object> session = new HashMap<>();
			
			if (isAnonymous) {
				log.debug("Creating Session for Anonymous User");
			}
			
			if (StringUtils.isNotBlank(username)) {
				session.put("username", username);
			} else {
				session.put("username", authUser);
			}
			if (StringUtils.isNotBlank(password)) {
				session.put("password", password);		
			}
			session.put("sessionid", UUID.randomUUID().toString());
			session.put("authid", RequestContextHolder.currentRequestAttributes().getSessionId());
			List<String> roles = new ArrayList<>();
			for (GrantedAuthority ga : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
				roles.add(ga.getAuthority());
			}
			session.put("roles", roles);
			
			sessionHolder.put(p, session);
		}

	}

	private String getUsername(Object p) {
		
		if (p instanceof UserDetails) {
			  return ((UserDetails)p).getUsername();
		} 
		return p.toString();
	}

	/* (non-Javadoc)
	 * @see org.saiku.web.service.ISessionService#logout(javax.servlet.http.HttpServletRequest)
	 */
	public void logout(HttpServletRequest req) {
		if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
			Object p = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (sessionHolder.containsKey(p)) {
				sessionHolder.remove(p);
			}
		}

		SecurityContextHolder.getContext().setAuthentication(null);
		SecurityContextHolder.clearContext();

		HttpSession session = req.getSession(false);

		if (session != null && !orbisAuthEnabled) { // Just invalidate if not under orbis authentication workflow
			session.invalidate();
		}
	}

	/* (non-Javadoc)
	 * @see org.saiku.web.service.ISessionService#authenticate(javax.servlet.http.HttpServletRequest, java.lang.String, java.lang.String)
	 */
	public void authenticate(HttpServletRequest req, String username, String password) {
		try {
			UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
			token.setDetails(new WebAuthenticationDetails(req));
			Authentication authentication = this.authenticationManager.authenticate(token);
			log.debug("Logging in with [{}]", authentication.getPrincipal());
			SecurityContextHolder.getContext().setAuthentication(authentication);
		}
		catch (BadCredentialsException bd) {
			throw new RuntimeException("Authentication failed for: " + username, bd);
		}

	}

	/* (non-Javadoc)
	 * @see org.saiku.web.service.ISessionService#getSession(javax.servlet.http.HttpServletRequest)
	 */
	public Map<String,Object> getSession() {
		if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {			
			Authentication auth = SecurityContextHolder.getContext().getAuthentication();
			Object p = auth.getPrincipal();

		  if (sessionHolder.containsKey(p)) {
			  Map<String, Object> r = new HashMap<>();
			  r.putAll(sessionHolder.get(p));
			  r.remove("password");

			  if (!r.containsKey("sessionid")) {
			    r.put("sessionid", UUID.randomUUID().toString());
			  }

			  return r;
		  }
		}

		return new HashMap<>();
	}
	
	public Map<String,Object> getAllSessionObjects() {
		if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {			
			Authentication auth = SecurityContextHolder.getContext().getAuthentication();
			Object p = auth.getPrincipal();
			//createSession(auth, null, null);
			if (sessionHolder.containsKey(p)) {
				Map<String,Object> r = new HashMap<>();
				r.putAll(sessionHolder.get(p)); 
				return r;
			}

		}
		return new HashMap<>();
	}

  public void clearSessions(HttpServletRequest req, String username, String password) throws Exception {
	if (authenticationManager != null) {
	  authenticate(req, username, password);
	}
	if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
	  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	  Object p = auth.getPrincipal();
	  if (sessionHolder.containsKey(p)) {
		sessionHolder.remove(p);
	  }
	}


  }


	public void setSessionRepo(org.saiku.repository.ScopedRepo sessionRepo) {
		this.sessionRepo = sessionRepo;
	}

	public Boolean isOrbisAuthEnabled() {
		return orbisAuthEnabled;
	}

	public void setOrbisAuthEnabled(Boolean orbisAuthEnabled) {
		this.orbisAuthEnabled = orbisAuthEnabled;
	}
}

saiku-ui\js\saiku\models\Session.js

/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Object which handles authentication and stores connections and cubes
 * @param username
 * @param password
 * @returns {Session}
 */
var Session = Backbone.Model.extend({
    username: null,
    password: null,
    sessionid: null,
    upgradeTimeout: null,
    isAdmin: Settings.ORBIS_AUTH.hazelcast_enabled,
    id: null,
	atemptedToLoginByCookie: false,
    initialize: function(args, options) {
        // Attach a custom event bus to this model
        _.extend(this, Backbone.Events);
        _.bindAll(this, "check_session", "process_session", "load_session","login", "brute_force");
        // Check if credentials are being injected into session
        if (options && options.username && options.password) {
            this.username = options.username;
            this.password = options.password;
            if (!Settings.DEMO) {
                this.save({username:this.username, password:this.password},{success: this.check_session, error: this.check_session});
            } else {
                this.check_session();
            }

        } else {
            this.check_session();
        }
    },

    check_session: function() {
		// This authentication cookie is used only by Orbis authentication strategy
		var authCookie = this.getCookie(Settings.ORBIS_AUTH.cookieName);

		if (Settings.ORBIS_AUTH.hazelcast_enabled && authCookie && !this.atemptedToLoginByCookie) {
            this.sessionid               = 1;
            this.username                = authCookie;
            this.password                = authCookie;
            this.atemptedToLoginByCookie = true;

            // In this case we inject the proper license attributes
            var ONE_YEAR = 31556952000;
            
            /**
            Settings.LICENSE = {
              licenseType: ‘Orbis‘,
              expiration: Date.now() + ONE_YEAR
            }
            */
            this.login(authCookie, authCookie);
		} else {
			if (this.sessionid === null || this.username === null || this.password === null) {
				var that = this;
				this.clear();
				this.fetch({ success: this.process_session, error: this.brute_force });
			} else {
                if (!this.atemptedToLoginByCookie) {
                    this.username = encodeURIComponent(options.username);
                }

				this.load_session();
			}
		}
    },

	getCookie: function(name) {
		var value = "; " + document.cookie;
		var parts = value.split("; " + name + "=");
        
		if (parts.length == 2) {
            var cookieVal = parts.pop().split(";").shift();
            return cookieVal;
        }
	},

	/**
	 * This is a complete hack to get the BI platform plugin working.
	 * @param obj
	 */
	brute_force: function(model, response){
		this.clear();
		this.fetch({ success: this.process_session, error: this.show_error });
	},
	show_error: function(model, response){

		// Open form and retrieve credentials
		Saiku.ui.unblock();
		this.form = new SessionErrorModal({ issue: response.responseText });
		this.form.render().open();


	},

    load_session: function() {
        this.sessionworkspace = new SessionWorkspace();
    },

    process_session: function(model, response) {
        if ((response === null || response.sessionid == null)) {
            // Open form and retrieve credentials
            Saiku.ui.unblock();
            if (Settings.DEMO) {
                this.form = new DemoLoginForm({ session: this });
            } else {
                this.form = new LoginForm({ session: this });
            }
            this.form.render().open();
        } else {
            this.sessionid = response.sessionid;
            this.roles = response.roles;
            this.isAdmin = Settings.ORBIS_AUTH.hazelcast_enabled || response.isadmin;
            this.username = encodeURIComponent(response.username);
            this.language = response.language;
            if (typeof this.language != "undefined" && this.language != Saiku.i18n.locale) {
                Saiku.i18n.locale = this.language;
                Saiku.i18n.automatic_i18n();
            }
            /**
                var license =new License();

                license.fetch_license(‘api/license/‘, function(opt) {
                    if (opt.status === ‘success‘) {
                        Settings.LICENSE = opt.data.toJSON();
                    }
                    if(Saiku.session.isAdmin) {

                        var quota = new LicenseQuota();

                        quota.fetch_quota(‘api/license/quota‘, function (opt) {
                            if (opt.status === ‘success‘) {
                                Settings.LICENSEQUOTA = opt.data.toJSON();
                            }
                        });
                    }

                });
			*/

            this.load_session();
        }

        return this;
    },

    error: function() {
        $(this.form.el).dialog(‘open‘);
    },

    login: function(username, password) {
        var that = this;
        this.save({username:username, password:password},{dataType: "text", success: this.check_session, error: function(model, response){
            that.login_failed(response.responseText);
        }});

    },
    login_failed: function(response){
        this.form = new LoginForm({ session: this });
        this.form.render().open();
        this.form.setError(response);
    },
    logout: function() {
        // FIXME - This is a hack (inherited from old UI)
        Saiku.ui.unblock();
        $(‘#header‘).empty().hide();
        $(‘#tab_panel‘).remove();
        Saiku.tabs = new TabSet();
        Saiku.toolbar.remove();
        Saiku.toolbar = new Toolbar();

        if (typeof localStorage !== "undefined" && localStorage) {
            localStorage.clear();
        }

        this.set(‘id‘, _.uniqueId(‘queryaction_‘));
        this.destroy({async: false });

        this.clear();
        this.sessionid = null;
        this.username = null;
        this.password = null;
		this.roles = null;
        this.isAdmin = false;
        this.destroy({async: false });
        //console.log("REFRESH!");
        document.location.reload(false);


    },

    url: function() {

        return "session";
    }
});

saiku-ui\js\saiku\views\Upgrade.js

/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * The global toolbar
 */
var Upgrade = Backbone.View.extend({

	events: {
	},


	initialize: function(a, b) {

		this.workspace = a.workspace;

		// Fire off workspace event
		this.workspace.trigger(‘workspace:toolbar:render‘, {
			workspace: this.workspace
		});

	},

	daydiff: function(first, second) {
		return Math.round((second-first)/(1000*60*60*24));
	},

	render: function() {
/*
		var self = this;
		var license = new License();

		if(Settings.BIPLUGIN5){
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>Notice:"+Saiku.session.get("notice")+"</div>");

				}
				if (Settings.LICENSE.licenseType != undefined && (Settings.LICENSE.licenseType != "trial" && Settings.LICENSE.licenseType != "Open Source License")) {
					return this;
				}
				if (Settings.LICENSE != undefined && Settings.LICENSE.licenseType === "trial") {
					var yourEpoch = parseFloat(Settings.LICENSE.expiration);
					var yourDate = new Date(yourEpoch);
					self.remainingdays = self.daydiff(new Date(), yourDate);


					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using a Saiku Enterprise" +
						" Trial license, you have "+ self.remainingdays+" days remaining. <a href=‘http://www.meteorite.bi/saiku-pricing‘>Buy licenses online.</a></div>");
					return self;
				}
				else {
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using Saiku Community" +
						" Edition, please consider upgrading to <a target=‘_blank‘ href=‘http://meteorite.bi‘>Saiku Enterprise</a>, or entering a <a href=‘http://meteorite.bi/products/saiku/sponsorship‘>sponsorship agreement with us</a> to support development. " +
						"<a href=‘http://meteorite.bi/products/saiku/community‘>Or contribute by joining our community and helping other users!</a></div></div>");

					return self;
				}
		}
		else {
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>Notice:"+Saiku.session.get("notice")+"</div>");

				}
				if (Settings.LICENSE.licenseType != undefined && (Settings.LICENSE.licenseType != "trial" &&
					Settings.LICENSE.licenseType != "Open Source License")) {
					return this;
				}
				if (Settings.LICENSE.licenseType === "trial") {
					var yourEpoch = parseFloat(Settings.LICENSE.expiration);
					var yourDate = new Date(yourEpoch);

					self.remainingdays = self.daydiff(new Date(), yourDate);

					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using a Saiku Enterprise" +
						" Trial license, you have "+ self.remainingdays+" days remaining. <a href=‘http://www.meteorite.bi/saiku-pricing‘>Buy licenses online.</a></div>");
					return self;
				}
				else {
					$(this.el).append("<div><div id=‘uphead‘ class=‘upgradeheader‘>You are using Saiku Community" +
						" Edition, please consider upgrading to <a target=‘_blank‘ href=‘http://meteorite.bi‘>Saiku Enterprise</a>, or entering a <a href=‘http://meteorite.bi/products/saiku/sponsorship‘>sponsorship agreement with us</a> to support development. " +
						"<a href=‘http://meteorite.bi/products/saiku/community‘>Or contribute by joining our community and helping other users!</a></div></div>");
					return self;
				}
		}




*/



	},

	call: function(e) {
	}

});

Saiku去掉License驗證信息以及數據備份(二十一)