calendar v3

This commit is contained in:
henrydays 2019-03-12 03:34:40 +00:00
parent 4b7909da4c
commit 116fc1b3a9
15 changed files with 412 additions and 176 deletions

View File

@ -104,10 +104,7 @@ const AppStack = createBottomTabNavigator(
}, },
{ {
//initialRouteName: 'Home', initialRouteName: 'Home',
initialRouteName: 'Eventos',
//initialRouteName: 'Calendário',
tabBarOptions: { tabBarOptions: {
showLabel: true, // hide labels showLabel: true, // hide labels
@ -125,7 +122,8 @@ const Stack = createStackNavigator({
screen: AppStack, screen: AppStack,
navigationOptions: ({navigation}) => { navigationOptions: ({navigation}) => {
const index = navigation.state.index; const index = navigation.state.index;
if (navigation.state.routes[index].routeName == 'Home') { if (navigation.state.routes[index].routeName == 'Home') {
return { return {
headerTitle: `${navigation.state.routes[index].routeName}`, headerTitle: `${navigation.state.routes[index].routeName}`,

View File

@ -19,7 +19,7 @@ import * as Progress from "react-native-progress";
import { connect } from "react-redux"; import { connect } from "react-redux";
import { bindActionCreators } from "redux"; import { bindActionCreators } from "redux";
import PTRView from 'react-native-pull-to-refresh';
import * as Actions from "../store/actions"; //Import your actionss import * as Actions from "../store/actions"; //Import your actionss
const formatObj = obj => { const formatObj = obj => {
@ -140,6 +140,10 @@ class Calendar extends React.Component {
constructor() { constructor() {
super(); super();
} }
_refresh=()=>{
this.props.getEvents(this.props.user);
this.props.getSessions(this.props.userDetails.token);
}
render() { render() {
const ThirdRoute = () => ( const ThirdRoute = () => (
@ -275,7 +279,9 @@ class Calendar extends React.Component {
); );
return ( return (
<View style={{ flex: 1 }}> <View style={{ flex: 1 }}>
<View> <View>
{this.props.careerPath != undefined && ( {this.props.careerPath != undefined && (
<Text <Text
@ -292,6 +298,7 @@ class Calendar extends React.Component {
</Text> </Text>
)} )}
</View> </View>
<TabView <TabView
navigationState={this.state} navigationState={this.state}
renderScene={SceneMap({ renderScene={SceneMap({
@ -310,7 +317,11 @@ class Calendar extends React.Component {
style={{ backgroundColor: "#F2F2F2" }} style={{ backgroundColor: "#F2F2F2" }}
indicatorStyle={{ backgroundColor: "pink" }} indicatorStyle={{ backgroundColor: "pink" }}
/> />
<Button onPress={this._refresh} title="Close" color="#841584"
accessibilityLabel="Learn more about this purple button"/>
</View> </View>
); );
} }
} }

View File

@ -155,10 +155,11 @@ _update=()=>{
<View style={styles.userImageContainer}> <View style={styles.userImageContainer}>
<Image style={styles.userImage} source={{uri: 'https://i.imgur.com/XXJ7LxV.jpg'}}/> <Image style={styles.userImage} source={{uri: 'https://i.imgur.com/XXJ7LxV.jpg'}}/>
</View> </View>
{this.props.user!=undefined &&
<Text style={styles.userText}>{this.props.user.Name}</Text> <Text style={styles.userText}>{this.props.user.Name}</Text>
}
<Text style={styles.userTextSub}>{this.props.user.Company}</Text> <Text style={styles.userTextSub}>{this.props.user.Company}</Text>
</View> </View>
</ImageBackground> </ImageBackground>

View File

@ -50,11 +50,12 @@ const formatObj = (obj) => {
class calendarDetail extends React.Component { class calendarDetail extends React.Component {
static navigationOptions = ({navigation}) => ({ static navigationOptions = ({navigation}) => ({
header: ( header: (
<NavAbsolute <NavAbsolute
navigation={navigation} navigation={navigation}
title={navigation.state.params.info.name} // title={navigation.state.params.info.name}
/> />
), ),
}); });
@ -67,6 +68,11 @@ class calendarDetail extends React.Component {
this.props.getEvents(this.props.user); this.props.getEvents(this.props.user);
console.log('didMount'); console.log('didMount');
console.log(this.props.events); console.log(this.props.events);
const {navigation} = this.props;
const info = navigation.getParam('info', 'error');
console.log("putas")
console.log(info)
} }
@ -103,29 +109,35 @@ class calendarDetail extends React.Component {
renderDescription = (info) => { renderDescription = (info) => {
return ( return (
<View> <View>
<View style={styles.cardContainer}> <View style={styles.header}>
<View style={{flexDirection: "row", alignItems: 'center', alignSelf:'center'}}> <View style={{flexDirection: "row", alignItems: 'center', alignSelf:'center'}}>
<Text style={styles.ramoText}>Onde está o ramo? xD </Text>
<View style={styles.timeText}> <View style={styles.timeText}>
<Text style={{color: "#CC1A17", fontSize: 15}}> <Text style={{color: "#CC1A17", fontSize: 15}}>
{info.time === info.timeEnd ? info.time : `${info.time} - ${info.timeEnd}`} {info.time === info.timeEnd ? info.time : `${info.time} - ${info.timeEnd}`}
</Text> </Text>
</View> </View>
</View> </View>
<View><Text style={{margin:10,marginTop:0, fontSize:20, color:'#CC1A17'}}>{info.name}</Text></View>
<View style={styles.details}>
<Text style={styles.nameAttendee}>Attendee Name</Text> <View style={{margin:10}}>
<Progress.Bar color={'#000000'} progress={info.Enrolled / info.MaxAttendees} height={10} <Progress.Bar color={'#000000'} progress={info.Enrolled / info.MaxAttendees} height={10}
unfilledColor={'white'} width={210}/> unfilledColor={'white'} width={210}/>
<Text style={{alignSelf: "center"}}>{info.Enrolled} / {info.MaxAttendees}</Text> <Text >{info.Enrolled} / {info.MaxAttendees}</Text>
</View>
<Divider style={{backgroundColor: '#000'}}/>
<View>
<Text style={{fontSize:15, color:'#CC1A17', padding:10}}>Descrição</Text>
<Text style={{paddingLeft:10, paddingRigh:10}}></Text>
</View> </View>
</View> </View>
<View style={styles.cardContainer}> <View style={styles.block}>
<Text style={{fontSize: 20, color: "#CC1A17"}}>Descrição</Text> <Text style={{fontSize: 20, color: "#CC1A17"}}>Descrição</Text>
<Divider style={{backgroundColor: '#000'}}/> <Divider style={{backgroundColor: '#000'}}/>
<View style={{marginTop: 10}}> <View style={{marginTop: 10}}>
<Text style={{fontSize: 10}}> <Text>
{info.description} {info.description}
</Text> </Text>
</View> </View>
@ -197,7 +209,7 @@ class calendarDetail extends React.Component {
render() { render() {
const {navigation} = this.props; const {navigation} = this.props;
const info = navigation.getParam('info', 'error'); const info = navigation.getParam('info', 'error');
console.log(info);
return ( return (
@ -209,15 +221,15 @@ class calendarDetail extends React.Component {
</View> </View>
{this.renderDescription(info)} {this.renderDescription(info)}
</View> </View>
<View style={styles.cardContainer}> <View style={styles.block}>
<Text style={{fontSize: 20, color: "#CC1A17"}}>Localização</Text> <Text style={{fontSize: 20, color: "#CC1A17"}}>Localização</Text>
<Divider style={{backgroundColor: '#000', marginBottom: 10}}/> <Divider style={{backgroundColor: '#000', marginBottom: 10}}/>
</View> </View>
</ScrollView> </ScrollView>
<Divider style={{backgroundColor: 'black'}}/> <Divider style={{backgroundColor: 'black'}}/>
{this.renderAttendee()}
</View> </View>
) )
@ -227,6 +239,12 @@ class calendarDetail extends React.Component {
const styles = StyleSheet.create({ const styles = StyleSheet.create({
block:{
marginTop:15,
backgroundColor:'white',
padding:20
},
AttendeeContainer: { AttendeeContainer: {
flexDirection: 'row', flexDirection: 'row',
height: 55, height: 55,
@ -286,8 +304,8 @@ const styles = StyleSheet.create({
ramoText: { ramoText: {
alignSelf: 'flex-start', alignSelf: 'flex-start',
marginBottom: 5, marginBottom: 5,
color: '#000', color: 'white',
fontSize: 20, fontSize: 17,
fontWeight: '400', fontWeight: '400',
}, },
@ -310,10 +328,17 @@ const styles = StyleSheet.create({
//marginBottom: 55, //marginBottom: 55,
}, },
header:{
flex: 1,
padding: 10,
backgroundColor: 'white',
borderRadius: 0,
},
cardContainer: { cardContainer: {
flex: 1, flex: 1,
padding: 10, padding: 10,
margin: 20, // margin: 20,
backgroundColor: 'white', backgroundColor: 'white',
borderRadius: 5, borderRadius: 5,
}, },
@ -412,7 +437,8 @@ function mapStateToProps(state, props) {
token: state.apiReducer.token, token: state.apiReducer.token,
user: state.apiReducer.user, user: state.apiReducer.user,
logged: state.apiReducer.logged, logged: state.apiReducer.logged,
events: state.apiReducer.events events: state.apiReducer.events,
careerPath: state.apiReducer.careerPath,
} }
} }

View File

@ -324,7 +324,14 @@ class choosePath extends React.Component {
<View style={styles.session}> <View style={styles.session}>
{this._verifySession(item[index].Id) && ( {this._verifySession(item[index].Id) && (
<TouchableOpacity <TouchableOpacity
onPress={() => {}} onPress={() => {
this.props.removeSession(
this.props.user,
this.props.userDetails.token,
item[index].Id
);
}}
style={{ flex: 1, alignSelf: "center" }} style={{ flex: 1, alignSelf: "center" }}
> >
<View> <View>
@ -339,11 +346,14 @@ class choosePath extends React.Component {
{!this._verifySession(item[index].Id) && ( {!this._verifySession(item[index].Id) && (
<TouchableOpacity <TouchableOpacity
onPress={() => { onPress={() => {
this.props.waitChangeGuest()
//this.props.waitChangeGuest()
this.props.signSession( this.props.signSession(
this.props.user,
this.props.userDetails.token, this.props.userDetails.token,
item[index].Id item[index].Id
); );
}} }}
style={{ flex: 1, alignSelf: "center" }} style={{ flex: 1, alignSelf: "center" }}
> >
@ -395,11 +405,12 @@ class choosePath extends React.Component {
</View> </View>
{(this.props.changingGuest || this.props.Blocks == true) && ( {(this.props.changingGuest || this.props.Blocks == true) && (
<View style={{ flex:1, height:SCREEN_HEIGHT*0.6, alignSelf:'center',}}>
<ActivityIndicator <ActivityIndicator
size="large" size="large"
color="red" color="red"
style={{ flex: 1, alignContent: "center" }} style={{ alignContent: "center" , alignSelf:'center', marginTop:SCREEN_HEIGHT*0.2}}
/> /></View>
)} )}
</ScrollView> </ScrollView>
</View> </View>

View File

@ -17,6 +17,7 @@ export const CHANGE_GUEST = 'CHANGE_GUEST'
export const GET_SESSIONS= 'GET_SESSIONS' export const GET_SESSIONS= 'GET_SESSIONS'
export const SIGN_SESSION= 'SIGN_SESSION' export const SIGN_SESSION= 'SIGN_SESSION'
export const WAIT_CHANGE='WAIT_CHANGE' export const WAIT_CHANGE='WAIT_CHANGE'
export const REMOVE_SESSION = 'REMOVE_SESSION'
//UI //UI

View File

@ -1,6 +1,6 @@
import { AsyncStorage } from "react-native"; import { AsyncStorage } from "react-native";
import { NetInfo , Alert} from "react-native"; import { NetInfo, Alert } from "react-native";
var _ = require("lodash"); var _ = require("lodash");
@ -20,7 +20,8 @@ import {
WAIT_CHANGE, WAIT_CHANGE,
SIGN_SESSION, SIGN_SESSION,
OPEN_MODAL, OPEN_MODAL,
LOADINGLOGIN LOADINGLOGIN,
REMOVE_SESSION
} from "./actionTypes"; //Import the actions types constant we defined in our actions } from "./actionTypes"; //Import the actions types constant we defined in our actions
import moment from "moment"; import moment from "moment";
@ -39,43 +40,36 @@ axios.defaults.baseURL = "http://enei2019.uingress.com/internal/api";
const map = require("lodash/fp/map").convert({ cap: false }); const map = require("lodash/fp/map").convert({ cap: false });
export function waitLogin() {
export function waitLogin(){
return dispatch=>{
dispatch({
type: LOADINGLOGIN,
});
}
}
//faz autenticação com API interna
export function loginInternal(userDetails){
axios.defaults.baseURL = "http://127.0.0.1:5000";
return dispatch => { return dispatch => {
axios.post('/api/login',{
"username": "cena",
"password": "password"
}).then(a=>{
console.log("sucesso!")
console.log(a)
}).catch(p=>{
console.log(p)
})
dispatch({ dispatch({
type: OPEN_MODAL, type: LOADINGLOGIN
}); });
}; };
} }
//faz autenticação com API interna
export function loginInternal(userDetails) {
axios.defaults.baseURL = "http://127.0.0.1:5000";
return dispatch => {
axios
.post("/api/login", {
username: "cena",
password: "password"
})
.then(a => {
console.log("sucesso!");
console.log(a);
})
.catch(p => {
console.log(p);
});
dispatch({
type: OPEN_MODAL
});
};
}
export function openModal(info, t) { export function openModal(info, t) {
return dispatch => { return dispatch => {
@ -124,27 +118,27 @@ function getCareerPath(sessions) {
for (let key in sessions) { for (let key in sessions) {
if (sessions[key].Name == "IA") { if (sessions[key].Name == "IA") {
careerPath = "Artificial Inteligence"; careerPath = "Artificial Inteligence";
careerColor='#CC1A17' careerColor = "#CC1A17";
} }
if (sessions[key].Name == "IOT") { if (sessions[key].Name == "IOT") {
careerPath = "Internet of Things"; careerPath = "Internet of Things";
careerColor= "green" careerColor = "green";
} }
if (sessions[key].Name == "WEB") { if (sessions[key].Name == "WEB") {
careerPath = "Web Development"; careerPath = "Web Development";
careerColor="purple" careerColor = "purple";
} }
if (sessions[key].Name == "NET") { if (sessions[key].Name == "NET") {
careerPath = "Networking and Security"; careerPath = "Networking and Security";
careerColor="blue" careerColor = "blue";
} }
if (sessions[key].Name == "MOB") { if (sessions[key].Name == "MOB") {
careerPath = "Mobile Development"; careerPath = "Mobile Development";
careerColor="orange" careerColor = "orange";
} }
if(sessions[key].Name=="DS"){ if (sessions[key].Name == "DS") {
careerPath="Data Science" careerPath = "Data Science";
careerColor="yellow" careerColor = "yellow";
} }
} }
return { name: careerPath, color: careerColor }; return { name: careerPath, color: careerColor };
@ -169,8 +163,84 @@ export const connectionState = status => {
return { type: "CHANGE_CONNECTION_STATUS", isConnected: status }; return { type: "CHANGE_CONNECTION_STATUS", isConnected: status };
}; };
export function removeSession(user,token, idSession) {
axios.defaults.headers.common = {
Authorization: `bearer ${token.access_token}`
};
var obj = {
IdSession: idSession,
Direction: 0
};
return dispatch => {
//adiciona participante a uma palestra
axios
.post("/Session/RemoveAttendee", obj)
//se não existir erro na chamada...
.then(a => {
console.log(a)
if (a.data.Success) {
axios
.get("/Attendee/AvailableSessions")
.then(function(response) {
console.log(response);
var sessions = response.data;
var careerPath = getCareerPath(sessions);
var cenas = [];
const result = flow(groupBy("SessionStart"))(response.data);
for (let key in result) {
result[key].option = 0;
cenas.push(result[key]);
}
Alert.alert("Sucesso","A inscrição na sessão foi removida com sucesso!");
//obter informações pessoais:
axios
.get("/Attendee/Detail")
.catch(error => {
alert(error);
})
.then(sucess => {
dispatch({
type: REMOVE_SESSION,
sessions: response.data,
Blocks: cenas,
changeGuestList: false,
careerPath: careerPath,
user: sucess.data
});
getEvents(user);
});
})
.catch(function(error) {
alert("Erro a obter sessões disponíveis!!");
console.log(error);
});
} else {
alert("Erro a inscrever na palestra");
dispatch({
type: REMOVE_SESSION,
waitChangeGuest: false
});
}
})
.catch(b => {
alert("Erro a inscrever na palestra");
});
};
}
//inscrição em palestra através de ID //inscrição em palestra através de ID
export function signSession(token, idSession) { export function signSession(user,token, idSession) {
axios.defaults.headers.common = { axios.defaults.headers.common = {
Authorization: `bearer ${token.access_token}` Authorization: `bearer ${token.access_token}`
}; };
@ -204,8 +274,8 @@ export function signSession(token, idSession) {
cenas.push(result[key]); cenas.push(result[key]);
} }
alert("Inscrição efectuada com sucesso"); Alert.alert("Sucesso","Inscrição na sessão efectuada com sucesso");
//obter informações pessoais: //obter informações pessoais:
axios axios
.get("/Attendee/Detail") .get("/Attendee/Detail")
@ -222,15 +292,16 @@ export function signSession(token, idSession) {
careerPath: careerPath, careerPath: careerPath,
user: sucess.data user: sucess.data
}); });
getEvents(user);
}); });
}) })
.catch(function(error) { .catch(function(error) {
alert("Erro a obter sessões disponíveis!!");
console.log(error); console.log(error);
}); });
} else { } else {
alert("Erro a inscrever na palestra");
Alert.alert("ERRO!!",a.data.Error);
dispatch({ dispatch({
type: SIGN_SESSION, type: SIGN_SESSION,
waitChangeGuest: false waitChangeGuest: false
@ -238,7 +309,8 @@ export function signSession(token, idSession) {
} }
}) })
.catch(b => { .catch(b => {
alert("Erro a inscrever na palestra"); // alert("Erro a inscrever na palestra");
}); });
}; };
} }
@ -327,7 +399,6 @@ export function getAvailableGuestlists(token) {
*/ */
export function changeGuestList(token, guestID) { export function changeGuestList(token, guestID) {
//http://enei2019.uingress.com/internal/api/Attendee/ChangeGuestlist/ //http://enei2019.uingress.com/internal/api/Attendee/ChangeGuestlist/
axios.defaults.headers.common = { axios.defaults.headers.common = {
@ -340,7 +411,7 @@ export function changeGuestList(token, guestID) {
axios axios
.get(full) .get(full)
.then(function(response) { .then(function(response) {
console.log(response) console.log(response);
axios.defaults.baseURL = "http://enei2019.uingress.com/internal/api"; axios.defaults.baseURL = "http://enei2019.uingress.com/internal/api";
axios.defaults.headers.common = { axios.defaults.headers.common = {
@ -355,7 +426,7 @@ export function changeGuestList(token, guestID) {
//console.log(response); //console.log(response);
var cenas = []; var cenas = [];
c= getCareerPath(response.data); c = getCareerPath(response.data);
const result = flow( const result = flow(
groupBy("SessionStart") groupBy("SessionStart")
// map((Id) => ({Id})), // map((Id) => ({Id})),
@ -463,10 +534,10 @@ export function getEvents(user) {
return dispatch => { return dispatch => {
let events = []; let events = [];
console.log("chegou aqui"); console.log("chegou aqui");
var i=0 var i = 0;
for (let key in user.Sessions) { for (let key in user.Sessions) {
events.push({ events.push({
key:i++, key: i++,
time: moment(user.Sessions[key].SessionStart).format("HH:mm"), time: moment(user.Sessions[key].SessionStart).format("HH:mm"),
timeEnd: moment(user.Sessions[key].SessionEnd).format("HH:mm"), timeEnd: moment(user.Sessions[key].SessionEnd).format("HH:mm"),
//lineColor:'#009688', //lineColor:'#009688',
@ -479,48 +550,43 @@ var i=0
day: moment(user.Sessions[key].SessionStart).format("DD") day: moment(user.Sessions[key].SessionStart).format("DD")
}); });
} }
const result = flow( const result = flow(groupBy("day"))(events);
groupBy("day")
)(events);
var cenas = [];
var cenas=[];
for (let key in result) { for (let key in result) {
cenas.push(result[key]); cenas.push(result[key]);
console.log(); console.log();
} }
console.log(".--------") console.log(".--------");
console.log(cenas); console.log(cenas);
console.log(".--------") console.log(".--------");
var a=[], b=[],c=[],d=[] var a = [],
b = [],
c = [],
d = [];
for (let key in cenas[0]) { for (let key in cenas[0]) {
a.push({ a.push({
time:cenas[0][key].time , time: cenas[0][key].time,
timeEnd: cenas[0][key].timeEnd, timeEnd: cenas[0][key].timeEnd,
imageUrl:cenas[0][key].imageUrl, imageUrl: cenas[0][key].imageUrl,
description: cenas[0][key].description, description: cenas[0][key].description,
name:cenas[0][key].name, name: cenas[0][key].name,
Enrolled: cenas[0][key].Enrolled, Enrolled: cenas[0][key].Enrolled,
MaxAttendees: cenas[0][key].MaxAttendees, MaxAttendees: cenas[0][key].MaxAttendees,
day: cenas[0][key].day day: cenas[0][key].day
}); });
} }
for (let key in cenas[1]) { for (let key in cenas[1]) {
b.push({ b.push({
time:cenas[1][key].time , time: cenas[1][key].time,
timeEnd: cenas[1][key].timeEnd, timeEnd: cenas[1][key].timeEnd,
imageUrl:cenas[1][key].imageUrl, imageUrl: cenas[1][key].imageUrl,
description: cenas[1][key].description, description: cenas[1][key].description,
name:cenas[1][key].name, name: cenas[1][key].name,
Enrolled: cenas[1][key].Enrolled, Enrolled: cenas[1][key].Enrolled,
MaxAttendees: cenas[1][key].MaxAttendees, MaxAttendees: cenas[1][key].MaxAttendees,
day: cenas[1][key].day day: cenas[1][key].day
@ -528,11 +594,11 @@ var i=0
} }
for (let key in cenas[2]) { for (let key in cenas[2]) {
c.push({ c.push({
time:cenas[2][key].time , time: cenas[2][key].time,
timeEnd: cenas[2][key].timeEnd, timeEnd: cenas[2][key].timeEnd,
imageUrl:cenas[2][key].imageUrl, imageUrl: cenas[2][key].imageUrl,
description: cenas[2][key].description, description: cenas[2][key].description,
name:cenas[2][key].name, name: cenas[2][key].name,
Enrolled: cenas[2][key].Enrolled, Enrolled: cenas[2][key].Enrolled,
MaxAttendees: cenas[2][key].MaxAttendees, MaxAttendees: cenas[2][key].MaxAttendees,
day: cenas[2][key].day day: cenas[2][key].day
@ -541,29 +607,35 @@ var i=0
for (let key in cenas[3]) { for (let key in cenas[3]) {
d.push({ d.push({
time:cenas[3][key].time , time: cenas[3][key].time,
timeEnd: cenas[3][key].timeEnd, timeEnd: cenas[3][key].timeEnd,
imageUrl:cenas[3][key].imageUrl, imageUrl: cenas[3][key].imageUrl,
description: cenas[3][key].description, description: cenas[3][key].description,
name:cenas[3][key].name, name: cenas[3][key].name,
Enrolled: cenas[3][key].Enrolled, Enrolled: cenas[3][key].Enrolled,
MaxAttendees: cenas[3][key].MaxAttendees, MaxAttendees: cenas[3][key].MaxAttendees,
day: cenas[3][key].day day: cenas[3][key].day
}); });
} }
a=_.sortBy(a, function(o) { return o.time; }); a = _.sortBy(a, function(o) {
b=_.sortBy(b, function(o) { return o.time; }); return o.time;
c=_.sortBy(c, function(o) { return o.time; }); });
d=_.sortBy(d, function(o) { return o.time; }); b = _.sortBy(b, function(o) {
return o.time;
});
c = _.sortBy(c, function(o) {
return o.time;
});
d = _.sortBy(d, function(o) {
return o.time;
});
dispatch({ dispatch({
type: GET_EVENTS, type: GET_EVENTS,
events:a, events: a,
day1:a, day1: a,
day2:b, day2: b,
day3:c, day3: c,
day4:d day4: d
}); });
}; };
} }
@ -653,54 +725,56 @@ export function login(user, pass) {
logged: false, logged: false,
failedAttempt: true, failedAttempt: true,
tokenData: "error", tokenData: "error",
user: { Name: "" }, user: { Name: "" }
}); });
}) })
.catch(err=>{ .catch(err => {
console.log("error") console.log("error");
}) })
.then(res => res.json()) .then(res => res.json())
.then(parsed => { .then(parsed => {
console.log(parsed) console.log(parsed);
if ( if (
parsed.error_description == parsed.error_description ==
"Provided username and password is incorrect" "Provided username and password is incorrect"
) { ) {
Alert.alert("Dados Inválidos","Podes sempre fazer reset da password para o email.") Alert.alert(
"Dados Inválidos",
"Podes sempre fazer reset da password para o email."
);
dispatch({ dispatch({
type: API_LOGIN, type: API_LOGIN,
logged: false, logged: false,
failedAttempt: true, failedAttempt: true,
token: obj, token: obj,
user: { Name: "Henrique" }, user: { Name: "Henrique" },
userDetails:{}, userDetails: {},
waitLogin:false, waitLogin: false,
onHold:false onHold: false
}); });
return; return;
} } else {
else{ var obj = {
var obj = { access_token: parsed.access_token,
access_token: parsed.access_token, expirationDateToken: Math.round(new Date().getTime() / 1000) + 3598,
expirationDateToken: Math.round(new Date().getTime() / 1000) + 3598, refreshToken: parsed.refresh_token,
refreshToken: parsed.refresh_token, valid: true
valid: true };
};
var details = { var details = {
username: user, username: user,
password: pass password: pass
}; };
dispatch({ dispatch({
type: API_LOGIN, type: API_LOGIN,
logged: true, logged: true,
failedAttempt: false, failedAttempt: false,
token: obj, token: obj,
user: { Name: "Henrique" }, user: { Name: "Henrique" },
userDetails: details userDetails: details
});} });
}
}); });
}; };
} }

View File

@ -16,7 +16,9 @@ export {checkUser,
openModal, openModal,
closeModal, closeModal,
loginInternal, loginInternal,
waitLogin waitLogin,
removeSession
} from "./api" } from "./api"
export { export {

View File

@ -15,8 +15,8 @@ import {
SIGN_SESSION, SIGN_SESSION,
OPEN_MODAL, OPEN_MODAL,
CLOSE_MODAL, CLOSE_MODAL,
LOADINGLOGIN LOADINGLOGIN,
REMOVE_SESSION
} from "../actions/actionTypes"; //Import the actions types constant we defined in our actions } from "../actions/actionTypes"; //Import the actions types constant we defined in our actions
import { REHYDRATE } from "redux-persist"; import { REHYDRATE } from "redux-persist";
@ -42,13 +42,12 @@ let apiState = {
sessions: {}, sessions: {},
Blocks: {}, Blocks: {},
onHoldBlocks: true, onHoldBlocks: true,
careerPath:{name:'Sem Career Path', color:'#eeeeee'}, careerPath: { name: "Sem Career Path", color: "#eeeeee" },
a:{}, a: {},
b:{}, b: {},
c:{}, c: {},
d:{}, d: {},
loadingLogin:false, loadingLogin: false
}; };
const apiReducer = (state = apiState, action) => { const apiReducer = (state = apiState, action) => {
@ -101,7 +100,7 @@ const apiReducer = (state = apiState, action) => {
}); });
case LOADINGLOGIN: case LOADINGLOGIN:
state= Object.assign({}, state, {loadingLogin:true}); state = Object.assign({}, state, { loadingLogin: true });
case HOLD: case HOLD:
state = Object.assign({}, state, { onHold: true }); state = Object.assign({}, state, { onHold: true });
@ -118,7 +117,7 @@ const apiReducer = (state = apiState, action) => {
username: action.userDetails.username, username: action.userDetails.username,
password: action.userDetails.password password: action.userDetails.password
}, },
loadingLogin:false, loadingLogin: false,
onHold: action.onHold onHold: action.onHold
}); });
@ -137,7 +136,11 @@ const apiReducer = (state = apiState, action) => {
return state; return state;
case LOGOUT_USER: case LOGOUT_USER:
state = Object.assign({}, state, { user:{}, userDetails:{}, logged:false}); state = Object.assign({}, state, {
user: {},
userDetails: {},
logged: false
});
return state; return state;
@ -151,12 +154,28 @@ const apiReducer = (state = apiState, action) => {
return state; return state;
case GET_EVENTS: case GET_EVENTS:
state = Object.assign({}, state, { events: action.events , a:action.day1, b:action.day2, c:action.day3, d:action.day4}); state = Object.assign({}, state, {
events: action.events,
a: action.day1,
b: action.day2,
c: action.day3,
d: action.day4
});
return state; return state;
case REMOVE_SESSION:
state = Object.assign({}, state, {
sessions: action.sessions,
Blocks: action.Blocks,
careerPath: action.careerPath,
changingGuest: action.changingGuest,
user: action.user
});
return state;
case OPEN_MODAL: case OPEN_MODAL:
console.log("open modal") console.log("open modal");
state = Object.assign({}, state, { state = Object.assign({}, state, {
modalOpen: true, modalOpen: true,
modalInfo: action.modalInfo, modalInfo: action.modalInfo,
@ -173,13 +192,25 @@ const apiReducer = (state = apiState, action) => {
return state; return state;
case SIGN_SESSION: case SIGN_SESSION:
state = Object.assign({}, state, {
if(action.sessions==undefined || action.Blocks==undefined || action.user==undefined){
state = Object.assign({}, state, {
changingGuest: false,
});
}
else{
state = Object.assign({}, state, {
sessions: action.sessions, sessions: action.sessions,
Blocks: action.Blocks, Blocks: action.Blocks,
careerPath: action.careerPath, careerPath: action.careerPath,
changingGuest: action.changingGuest, changingGuest: false,
user:action.user user: action.user
}); });
}
return state; return state;
case SESSION_BLOCKS: case SESSION_BLOCKS:

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -14,6 +15,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
namespace api.Controllers namespace api.Controllers
{ {
@ -30,15 +32,18 @@ namespace api.Controllers
public IUsersRepository _repo { get; } public IUsersRepository _repo { get; }
private readonly IMapper _mapper; private readonly IMapper _mapper;
private readonly RoleManager<Role> _roleManager; private readonly RoleManager<Role> _roleManager;
private readonly System.Net.Http.IHttpClientFactory clientFactory;
public AuthController(IConfiguration config, UserManager<User> UserManager, SignInManager<User> SignInManager, IMapper mapper, RoleManager<Role> roleManager, IUsersRepository repo) public AuthController(IConfiguration config, UserManager<User> UserManager, SignInManager<User> SignInManager, IMapper mapper, RoleManager<Role> roleManager, IUsersRepository repo, System.Net.Http.IHttpClientFactory clientFactory)
{ {
_mapper = mapper; _mapper = mapper;
_roleManager = roleManager; _roleManager = roleManager;
_repo = repo; _repo = repo;
this.clientFactory = clientFactory;
this.config = config; this.config = config;
_userManager = UserManager; _userManager = UserManager;
_signInManager = SignInManager; _signInManager = SignInManager;
} }
@ -80,6 +85,40 @@ namespace api.Controllers
} }
[HttpPost("loginQR")]
public async Task<IActionResult> loginQr(UserForLoginDto userLoginDTO){
var token= "_A6q1cVGa12QutCrYCsYETfz9nPspnbcnPqjD-87kDaYPr99ArEfpdRTbkEzA4p-WEJzPFQhsMX7nG5BmUm0E6RTju8vQHnaTjGd80NIqUCr-jXefUtGwyl6I00fGD4sN6psW714JnCFuZRbtZbIXsdIRKmD3b8YUpPo2lvYP8SzjoEgACyabj13T3CLpHF43PI8Dvny6ylW6j0ka5qGNvw5MHVvYFURUPiTA7hlxoyQ35eOqHE8-eIiLNSTUJW7q-o8CxIGqGWSkltKPxbrY-Xo5iYagUucesqmj64VxYs";
using (var client = new HttpClient())
{
try{
var url = "http://enei2019.uingress.com/internal/api/Attendee/Detail";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var response = await client.GetStringAsync(url);
Console.WriteLine(response);
//var resource = JObject.Parse(response);
return Ok(response);
}catch(Exception e){
Console.WriteLine(e);
return Unauthorized();
}
}
}
private async Task<string> GenerateJwtToken(User user) private async Task<string> GenerateJwtToken(User user)
{ {
var claims = new List<Claim> var claims = new List<Claim>

23
api/Dtos/tokenDto.cs Normal file
View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using api.Models;
namespace api.Dtos
{
public class tokenDto
{
public string access_token{get;set;} //teamid
public string token_type{get;set;} //user qr
public int expires_in{get;set;}
public string refresh_token{get;set;}
}
}

18
api/Dtos/userDetails.cs Normal file
View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using api.Models;
namespace api.Dtos
{
public class userDetails
{
public string name{get;set;} //teamid
public string qr{get;set;} //user qr
}
}

View File

@ -42,7 +42,7 @@ namespace api
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddHttpClient();
services.AddAutoMapper(); services.AddAutoMapper();
services.AddScoped<IUsersRepository, UsersRepository>(); services.AddScoped<IUsersRepository, UsersRepository>();
services.AddScoped<IEventsRepository, EventsRepository>(); services.AddScoped<IEventsRepository, EventsRepository>();

View File

@ -3,12 +3,13 @@
<TargetFramework>netcoreapp2.1</TargetFramework> <TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Folder Include="wwwroot\"/> <Folder Include="wwwroot\" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0"/> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.1"/> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="5.0.1"/> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0"/> <PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.2.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,5 +1,5 @@
{ {
"ProjectFilePath": "c:\\Users\\ZMiguel\\Desktop\\ENEI2019\\api\\api.csproj", "ProjectFilePath": "/Users/henrique/ENEI2019/api/api.csproj",
"TargetFramework": "netcoreapp2.1", "TargetFramework": "netcoreapp2.1",
"TagHelpers": [], "TagHelpers": [],
"Configuration": { "Configuration": {