de.sainth.recipe.backend.rest.controller.LogoutController.java Source code

Java tutorial

Introduction

Here is the source code for de.sainth.recipe.backend.rest.controller.LogoutController.java

Source

/*
 * Copyright (c) 2017 sainth (sainth@sainth.de)
 *
 * 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, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package de.sainth.recipe.backend.rest.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

@RestController
@RequestMapping("/logout")
public class LogoutController {

    @RequestMapping()
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void logout(HttpServletRequest request, HttpServletResponse response) {
        if ("/logout".equals(request.getServletPath())) {
            Optional<Cookie> cookie = Arrays.stream(request.getCookies())
                    .filter(c -> "recipe_bearer".equals(c.getName())).findFirst();
            if (cookie.isPresent()) {
                Cookie c = cookie.get();
                c.setValue("");
                c.setPath("/");
                c.setMaxAge(0);
                response.addCookie(c);
            }
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }
}